SwiftUI:未导出变量字符串进行本地化

blu*_*Fox 3 localization swiftui

根据 Apple 文档,这应该有效:

\n
\n

如果您使用字符串变量而不是字符串文字来初始化文本视图,则该视图会触发 init( :) 初始值设定项,因为它假定您在这种情况下不需要本地化。如果您确实想要本地化存储在字符串变量中的值,您可以选择通过首先从字符串变量创建 LocalizedStringKey 实例来调用 init( :tableName:bundle:comment:) 初始值设定项:

\n

Text(LocalizedStringKey(someString)) // 本地化someString.

\n

https://developer.apple.com/documentation/swiftui/text/init(_:表名:bundle:comment:)

\n
\n

这里也推荐: https: //www.ibabbleon.com/swiftui_localization_tutorial.html

\n

然而,至少就我而言,事实并非如此。在以下示例中,仅导出“Some content 1”值以进行本地化。

\n
struct ContentView: View {\n    let text = "Some content 2"\n    var body: some View {\n        Text("Some content 1", comment: "This text is exported for localization, as expected.")\n            .padding()\n        Text(LocalizedStringKey(text), comment: "This text is not exported for localization, which is not expected behaviour.")\n            .padding()\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在应用程序设置中,“使用编译器提取 swift 字符串”设置为“是”。

\n

我缺少什么?

\n

blu*_*Fox 5

好吧,在对本地化进行了更多修改之后,我发现了一种效果很好的方法。

我链接到的教程(https://www.ibabbleon.com/swiftui_localization_tutorial.html)没有讨论这一点,并且使 LocalizedStringKey 和 Text(String, comment: String) 感到困惑。其他一些教程也遵循这条路线,但它使代码非常丑陋,因为它将数据移动到文本中。因此,如果您想将数据与视图分离,则必须在视图模型中包含文本(UI 元素)。或者,如果您使用 LocalizedStringKey,则无法包含翻译者的注释。

幸运的是,有一种更简单的方法!

struct ContentView: View {
  let normalString = "This is not exported for localization. Good for previews!"
  let localizedString = String(localized: "This is exported for localization.", comment: "You can add a comment for the translator, too!")

  var body: some View {
    VStack {
      Text(normalString)
      Text(localizedString)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)