SwiftUI预览中.stringsdict复数化失效问题求助
SwiftUI预览中复数文本正常显示的解决方案
不少开发者都碰到过这个Xcode预览的复数渲染问题——运行时.stringsdict的复数规则正常生效,但预览里就是不工作。下面是经过验证的可行解决办法:
显式指定本地化环境
Xcode预览有时会默认使用系统的基础本地化,导致复数规则不触发。在预览代码里手动指定目标locale就能解决:struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environment(\.locale, Locale(identifier: "zh-Hans")) // 替换为你的目标语言标识符 } }修正Bundle的加载逻辑
Bundle.module在预览环境下偶尔会出现识别异常,你可以换一种方式获取模块bundle:// 在视图中替换Bundle.module let targetBundle = Bundle(for: ContentView.self) Text("days \(1)", tableName: "Pluralized", bundle: targetBundle)或者通过环境变量传递bundle到视图:
// 预览代码 struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environment(\.locale, Locale(identifier: "zh-Hans")) .environment(\.bundle, Bundle.module) } } // 视图代码 struct ContentView: View { @Environment(\.bundle) private var currentBundle var body: some View { Text("days \(1)", tableName: "Pluralized", bundle: currentBundle) } }清理Xcode缓存并重启
这是解决Xcode预览玄学问题的常规操作:- 打开Xcode设置,进入
Locations标签页,点击Derived Data旁的箭头打开文件夹 - 删除文件夹内的所有内容
- 重启Xcode并重新构建预览
- 打开Xcode设置,进入
校验.stringsdict配置
确保你的复数规则文件配置正确,比如中文环境下的示例配置:<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>days</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@days@</string> <key>days</key> <dict> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>NSStringFormatValueTypeKey</key> <string>d</string> <key>zero</key> <string>0天</string> <key>one</key> <string>1天</string> <key>other</key> <string>%d天</string> </dict> </dict> </dict> </plist>同时要确认该文件已添加到目标的
Copy Bundle Resources构建阶段中。
内容的提问来源于stack exchange,提问作者esilver
相关产品推荐
相关产品推荐

