【问题标题】:How to translate / localize a variable in Swift如何在 Swift 中翻译/本地化变量
【发布时间】:2021-09-09 19:05:32
【问题描述】:

我有这个代码并且我已经成功地进行了本地化设置。我创建了一个Categories.strings 文件并对其进行了本地化,但类别的翻译不起作用。

代码:

struct CategoriesViewRow: View {
    var selection: SimpleJson

    var body: some View {
        HStack {
            Image(selection.name)
                .resizable()
                .scaledToFit()
                .frame(width: 20, height: 20)
            Text(String(localized: "\(selection.name)", table: "Categories", comment: "Category"))
            Spacer()
        }
    }
}

这个var selection: SimpleJson 是一个看起来像这样的结构:

struct SimpleJson: Hashable, Codable, Identifiable {
    var id: Int
    
    var name: String
    var description: String?
    var hidden: Bool?
}

它包含一些从文件加载的静态类别。它们需要从文件中加载,我总是设法在 Objective-C 中翻译它们。但现在在 Swift 中,我好像漏掉了什么。

正常 SwiftUI Text() 代码被正确翻译,但我的其他代码有问题。

我目前正在使用 Xcode Beta 13.0,但我很确定这不是问题所在。我宁愿认为我做错了什么,但我似乎无法为我的用例找到一些好的信息。

谁能帮帮我?

提前致谢

【问题讨论】:

    标签: swift xcode swiftui localization


    【解决方案1】:

    您可以将此函数添加到字符串扩展,然后在字符串变量上调用 .localize():

    extension String {
        /**
         So that when you return a String it also adjusts the language
         - Parameter comment: To describe specific meaning if it's unclear (e.g.: bear could mean the animal or the verb to bear)
         - Returns: The localized String duh
         - Usage: str.localize()
         - Further reading: https://www.hackingwithswift.com/example-code/uikit/how-to-localize-your-ios-app
         */
        func localize(comment: String = "") -> String {
            NSLocalizedString(self, comment: comment)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多