Gen*_*ich 1 string nslocalizedstring ios swift swiftui
我正在尝试解决一个看似简单的问题:在 SwiftUIText视图中向用户显示免费试用条款。我设置了一个单位字符串"Week"和 a value,可以从 1 切换到 2。为了处理复数,我利用了 iOS 15 上的自动语法协议。我的Localizable.strings文件中已经准备好了一个字符串,如下所示:
"Subscription period: %lld %@" = "^[%lld ^[%@](grammar: { partOfSpeech: \"noun\" })](inflect: true)";
Run Code Online (Sandbox Code Playgroud)
为了构建字符串,我需要使用字符串插值来添加单词“free”。我知道在字符串文件中添加单词可以解决问题,但我不想这样做。我想普遍使用该字符串,不一定与免费试用有关。我不明白为什么我不能调用一些 init,向它传递一个密钥,并返回一个我可以根据需要进行插值的纯字符串。我已经尝试了很多方法,在所附的代码片段中展示了这些方法。要么找不到该字符串,要么未应用自动语法协议。似乎有String.LocalizationValue.StringInterpolation结构,但我不知道如何使用它,因为没有任何文档。我究竟做错了什么?我将不胜感激任何帮助!
"Subscription period: %lld %@" = "^[%lld ^[%@](grammar: { partOfSpeech: \"noun\" })](inflect: true)";
Run Code Online (Sandbox Code Playgroud)
您可以在此处下载示例项目。
我实际上非常接近这段代码:
Text("\(String(localized: String.LocalizationValue("Subscription period: \(value) \(unit)"))) free")
Run Code Online (Sandbox Code Playgroud)
但使用方法String(localized:)并不正确。我猜这是因为自动语法协议使用了markdown,这是AttributedString. 我们应该使用AttributedString(localized:). 但即便如此,它也不会改变,因为显然基金会存在一个错误。但一旦修补好,它就会像魅力一样发挥作用。
这是正确的解决方案:
func freeTrialDuration() -> Text {
// Use plain string.
let duration: String = "^[\(value) ^[\(unit.lowercased())](grammar: { partOfSpeech: \"noun\" })](inflect: true)"
// Use the following way to get the localized string.
let localizedDuration = AttributedString(localized: String.LocalizationValue(duration))
return Text("\(localizedDuration) free")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1982 次 |
| 最近记录: |