Xcode模拟器无法切换AM/PM时间格式,Swift快照测试云端失败求助
解决Xcode 16模拟器AM/PM时间格式设置问题
以下是几种可行的解决方案,覆盖本地调试、测试代码配置、Scheme全局设置三种场景:
方法1:命令行强制修改模拟器时间格式
通过修改模拟器的偏好设置文件,强制启用12小时制(AM/PM格式):
- 获取目标模拟器的UDID:
- 打开Xcode,点击
Window > Devices and Simulators,选中要修改的模拟器,右侧面板可查看UDID; - 或执行命令:
xcrun simctl list devices,从输出中找到对应模拟器的UDID。
- 打开Xcode,点击
- 执行修改命令(替换
<UDID>为实际模拟器ID):defaults write ~/Library/Developer/CoreSimulator/Devices/<UDID>/data/Library/Preferences/.GlobalPreferences.plist AppleICUForce12HourTime -bool true - 重启模拟器生效:
xcrun simctl shutdown <UDID> && xcrun simctl boot <UDID>
方法2:在测试代码中强制设置Locale
避免依赖系统环境,直接在测试用例中指定使用AM/PM格式的区域设置:
import XCTest class YourSnapshotTest: XCTestCase { override func setUp() { super.setUp() // 强制设置为使用12小时制的Locale(例如美国英文) Locale.current = Locale(identifier: "en_US_POSIX") // 如果项目中使用自定义日期格式化器,也可以单独为其设置Locale let customDateFormatter = DateFormatter() customDateFormatter.locale = Locale(identifier: "en_US_POSIX") customDateFormatter.timeStyle = .short // 会自动使用AM/PM格式 } }
方法3:通过Xcode Scheme设置全局环境变量
为测试阶段添加环境变量,让模拟器启动时自动启用12小时制:
- 打开Xcode,点击
Product > Scheme > Edit Scheme; - 切换到
Test标签页,在Environment Variables区域点击+号; - 添加键
AppleICUForce12HourTime,值设为YES,并勾选变量前的复选框启用; - 保存Scheme后重新运行测试,模拟器会自动使用AM/PM时间格式。
内容的提问来源于stack exchange,提问作者TheKingArthas
相关产品推荐
相关产品推荐

