付出Bundle强制切换钦赐国家的言语

在做跨国项目标时候时不时要求接纳本地化的技术,可是在支付进度中多次须求交给给测试者贰个测试人士能够看得懂的版本,通过runtime机制得以兑现强制行使使用钦点语言,具体代码如下:

var kBundleKey = "kBundleKey"
class ExBundle: Bundle {
    override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        let b = objc_getAssociatedObject(self, &kBundleKey) as? Bundle
        if b == nil { return super.localizedString(forKey: key, value: value, table: tableName) }
        return b!.localizedString(forKey: key, value: value, table: tableName)
    }
}

第3创制二个ExBundle类继承自Bundle,重写方法localizedString,这些格局无论加在localizable.strings文件照旧采用xib大概storyboard文件的多语言时都会调用该方法,例如你调用NSLocalizedString最终应用会调用Bundle的localizedString去找寻钦点tableName下的key并重回值。再来看上面包车型大巴代码:

// AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        object_setClass(Bundle.main, ExBundle.classForCoder())
        let path = Bundle.main.path(forResource: "zh-Hans", ofType: "lproj")
        let bundle = Bundle.init(path: path!)
        objc_setAssociatedObject(Bundle.main, &kBundleKey, bundle, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        return true
    }

由此runtime机制,将Bundle.main对象的品种设置为ExBundle,并且通过objc_setAssociatedObject方法为Bundle.main对象设置一个为bundle属性,该bundle对象正是指向钦定多语言的文书夹。
末了只要程序内有其余利用多语言的地点,都会遵照kBundleKey取出bundle对象,通过bundle对象的localizedString来回到文言。

相关文章