如何设置画布预览语言?

Dio*_*uza 5 xcode localization swift swiftui

(目前正在 Xcode 11 Beta 7 上尝试)

\n\n

我想将已经本地化的字符串传递给 Text() 并使用“.environment(.locale, .init(identifier:"ja"))”查看它在画布上的外观,但预览始终设置为我选择的任何语言已设置方案设置。

\n\n

我知道如果我直接传递 LocalizedStringKey (如 Text("introTitle") ),它会起作用,但我不想这样做。相反,我想使用枚举,例如 Text(L10n.Intro.title),但是当我这样做时,环境运算符会被方案设置语言覆盖。

\n\n

这是错误还是预期行为?

\n\n
struct ContentView: View {\n    var body: some View {\n        Text("introTitle") //this works\n        Text(L10n.Intro.title) //this doesn\'t\n    }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n    static var previews: some View {\n        ForEach(["en", "ja", "pt"], id: \\.self) { localeIdentifier in\n            ContentView()\n                .environment(\\.locale, .init(identifier: localeIdentifier)) //this gets ignored, and only the scheme settings language is previewed\n                .previewDisplayName(localeIdentifier)\n        }\n    }\n}\n\ninternal enum L10n {\n  internal enum Intro {\n    internal static let title = NSLocalizedString("introTitle", comment: "")\n    internal static let title2 = "introTitle" //this also doesn\'t work\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Localized.strings中我有:

\n\n

//英语

\n\n

"introTitle" = "Welcome!";

\n\n

//日本人

\n\n

"introTitle" = "\xe3\x82\x88\xe3\x81\x86\xe3\x81\x93\xe3\x81\x9d!";

\n\n

//葡萄牙语

\n\n

"introTitle" = "Bem-vindo(a)!";

\n

LuL*_*aGa 2

我的首选方法是使用Text("introTitle"),但如果您想使用枚举作为本地化键,则必须像这样声明它

internal enum L10n {
  internal enum Intro {
    internal static let title = LocalizedStringKey("introTitle")
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以像这样使用它:

Text(L10n.Intro.title)
Run Code Online (Sandbox Code Playgroud)

在您的代码中title,类型为NSLocalisedStringtitle2是 a String,但您需要LocalizedStringKey将其传递到文本初始化程序中。