![](/img/trans.png)
[英]How to change LocalizedStringKey to String in SwiftUI
[英]How to get string value from LocalizedStringKey?
我正在使用LocalisedStringKey和以下代碼的幫助本地化我的 SwiftUI 應用程序:
Text(l10n.helloWorld)
其中l10n
是:
enum l10n {
internal static let helloWorld = LocalizedStringKey("hello.world")
}
其中"hello.world"
在文件Localizable.strings
定義:
"hello.world" = "Hello world !";
雖然這段代碼在 SwiftUI 的View
是這樣工作的:
...
Text(i18n.helloWorld)
...
我在后面的代碼中找不到從LocalizedStringKey
獲取 l10n 值的方法,如下所示:
l10n.helloWorld.toString()
我通常會創建一個自定義String
enum
並使用函數進行本地化。
import SwiftUI
struct LocalizeSample: View {
var body: some View {
Text(l10n.helloWorld.localize())
l10nText(text: .helloWorld)
}
}
struct l10nText: View {
var text: l10n
var body: some View {
Text(text.localize())
}
}
enum l10n: String {
case helloWorld = "hello.world"
func localize() -> String {
return NSLocalizedString(self.rawValue, comment: "l10n default")
}
}
struct LocalizeSample_Previews: PreviewProvider {
static var previews: some View {
LocalizeSample()
}
}
我認為這是因為 SwiftUI 並不是要從代碼后面進行本地化,所有本地化都必須在視圖聲明中進行。
但是,有一種方法可以通過擴展方法來實現:
extension LocalizedStringKey {
/**
Return localized value of thisLocalizedStringKey
*/
public func toString() -> String {
//use reflection
let mirror = Mirror(reflecting: self)
//try to find 'key' attribute value
let attributeLabelAndValue = mirror.children.first { (arg0) -> Bool in
let (label, _) = arg0
if(label == "key"){
return true;
}
return false;
}
if(attributeLabelAndValue != nil) {
//ask for localization of found key via NSLocalizedString
return String.localizedStringWithFormat(NSLocalizedString(attributeLabelAndValue!.value as! String, comment: ""));
}
else {
return "Swift LocalizedStringKey signature must have changed. @see Apple documentation."
}
}
}
遺憾的是,您必須使用Reflection
來實現這一點,因為key
在LocalizedStringKey
有一個internal
保護級別,使用風險自負。
使用 asis :
let s = l10n.helloWorld.toString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.