Use default language fallback when key is untranslated

混江龙づ霸主 提交于 2019-12-01 09:28:35

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!