iOS 开发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)
    }
}

首先创建一个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来回到文言。

Leave a Comment.