簡體   English   中英

如何從 LocalizedStringKey 獲取字符串值?

[英]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來實現這一點,因為keyLocalizedStringKey有一個internal保護級別,使用風險自負。

使用 asis :

let s = l10n.helloWorld.toString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM