【问题标题】:SwiftUI Text and LocalizedStringKey with parameterSwiftUI 文本和带参数的 LocalizedStringKey
【发布时间】:2021-10-04 15:57:46
【问题描述】:

我正在尝试添加带有参数的 SwiftUI 本地化文本。然而,在整个应用程序中,我们使用本地化键的包装器,所以我们有这样的东西:

static let helloWorldText = NSLocalizedString("helloWorldText", comment: "")

有用法

label.text = LocalizationWrapper.helloWorldText

Text(LocalizationWrapper.helloWorldText)

而且效果很好。

然后,当涉及到添加带有参数的本地化文本时,它似乎不起作用。

所以我有一把钥匙"helloWorld %@"

我有一个static let helloWorldWithParameter = NSLocalizedString("helloWorld %@", comment: "")

现在我尝试这样做:

Text("\(LocalizationWrapper.helloWorldWithParameter) \(name)")
Text(LocalizedStringKey(LocalizationWrapper.helloWorldWithParameter + " " + name))
Text(LocalizationWrapper.helloWorldWithParameter + " " + name)

它们都不起作用,但是 Text("helloWorld \(name)") 可以正常工作。

然后我尝试删除 NSLocalizedString 只留下 LocalizationWrapper.helloWorldWithParameter 作为一个干净的字符串,但它也没有做任何事情

我怎样才能做到这一点?我看过THIS,但它有点脏。

【问题讨论】:

  • 使用static func helloWorldText(_ str: String) { } -> String 怎么样?然后Text(LocalizationWrapper.helloWorldText(name))?
  • 使用 Text("(LocalizationWrapper.helloWorldWithParameter) (name)") 可以正常工作。你确定你在.string文件helloWorld %@中设置了完全相同的键吗?
  • @RajaKishan 我刚刚检查过,它不起作用,这里有一个截图ibb.co/bF9kwzr
  • @MaciejZajda 如果可能,请附上示例演示项目。
  • @RajaKishan 我给你发了一个在 github 上 repo 的邀请

标签: ios swift swiftui nslocalizedstring localizedstringkey


【解决方案1】:

使用这个扩展

extension String {
    public func localized(with arguments: [CVarArg]) -> String {
        return String(format: NSLocalizedString(self, comment: ""), locale: nil, arguments: arguments)
    }
}

用法:

Text(LocalizationWrapper.helloWorldWithParameter.localized(with: [name]))

另外,这个方法是正确的

static func helloWithParameter(parameter: String) -> LocalizedStringKey {
    return "helloWorld \(parameter)"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多