Use default language fallback when key is untranslated

前端 未结 1 1273
一生所求
一生所求 2021-01-14 08:09

Can i use default language (e.g. English) for untranslated keys in my other language Localizable.strings files ?

1条回答
  •  -上瘾入骨i
    2021-01-14 08:48

    To achieve this, you could use the English words as the keys in the Localizable.strings file.

    Another approach would be to check the outcome of NSLocalizedString and return the default english version (using a 'forced' bundle) in case the result is the same as the key.

    It could look something like this

    extension NSString {
        class func NSLocalizedStringWithDefault (key:String, comment:String)->String {
            let message = NSLocalizedString(key, comment: comment)
            if message != key {
                return message
            }
            let language = "en"
            let path = NSBundle.mainBundle().pathForResource(language, ofType: "lproj")
            let bundle = NSBundle(path: path!)
            if let forcedString = bundle?.localizedStringForKey(key, value: nil, table: nil){
                return forcedString
            }else {
                return key
            }
        }
    }
    

    Localized.string (eng)

    "test-key-1" = "Test 1";
    "test-key-2" = "Test 2";
    

    Localized.string (esp)

    "test-key-1" = "El Test 1";
    

    then you could use it like this (assuming locale set to 'es'):

    println(NSString.NSLocalizedStringWithDefault("test-key-1", comment: "")) // El Test 1
    println(NSString.NSLocalizedStringWithDefault("test-key-2", comment: "")) // Test 2 (from eng file)
    

    Not the cleanest way to implement, but you get the idea.

    0 讨论(0)
提交回复
热议问题