Mac*_*jda 3 nslocalizedstring ios swift swiftui localizedstringkey
我正在尝试添加带有参数的 SwiftUI 本地化文本。然而,在整个应用程序中,我们使用本地化键的包装器,所以我们有这样的东西:
static let helloWorldText = NSLocalizedString("helloWorldText", comment: "")
Run Code Online (Sandbox Code Playgroud)
随着使用
label.text = LocalizationWrapper.helloWorldText
Run Code Online (Sandbox Code Playgroud)
或者
Text(LocalizationWrapper.helloWorldText)
Run Code Online (Sandbox Code Playgroud)
而且效果很好。
然后,当涉及到添加带有参数的本地化文本时,它似乎不起作用。
所以我有一把钥匙"helloWorld %@"
我有一个static let helloWorldWithParameter = NSLocalizedString("helloWorld %@", comment: "")
现在我尝试这样做:
Text("\(LocalizationWrapper.helloWorldWithParameter) \(name)")
Text(LocalizedStringKey(LocalizationWrapper.helloWorldWithParameter + " " + name))
Text(LocalizationWrapper.helloWorldWithParameter + " " + name)
Run Code Online (Sandbox Code Playgroud)
它们都不起作用,但Text("helloWorld \(name)")效果很好。
然后我尝试删除 NSLocalizedString 只留下LocalizationWrapper.helloWorldWithParameter一个干净的字符串,但它也没有做任何事情
我怎样才能做到这一点?我看过这个,但有点脏。
使用此扩展
extension String {
public func localized(with arguments: [CVarArg]) -> String {
return String(format: NSLocalizedString(self, comment: ""), locale: nil, arguments: arguments)
}
}
Run Code Online (Sandbox Code Playgroud)
用法 :
Text(LocalizationWrapper.helloWorldWithParameter.localized(with: [name]))
Run Code Online (Sandbox Code Playgroud)
另外,这个方法是正确的
static func helloWithParameter(parameter: String) -> LocalizedStringKey {
return "helloWorld \(parameter)"
}
Run Code Online (Sandbox Code Playgroud)