自己写一个工具类DAConfig;
一个Bundle的子类NSBundleEx;
一个Bundle的扩展协议;
class DAConfig: NSObject {
static let UWUserLanguageKey = "UWUserLanguageKey"
class func setUserLanguage(userLanguage:String){
if userLanguage.count == 0 {
DAConfig.resetSystemLanguage()
return;
}
UserDefaults.standard.set(userLanguage, forKey: DAConfig.UWUserLanguageKey) UserDefaults.standard.set([userLanguage], forKey: "AppleLanguages") UserDefaults.standard.synchronize()
}
class func getUserLanguage() -> String{
Bundle.main.onLanguage()
return ( UserDefaults.standard.object(forKey: DAConfig.UWUserLanguageKey) ?? NSLocale.preferredLanguages.first!) as! String
}
class func resetSystemLanguage() {
UserDefaults.standard.removeObject(forKey: DAConfig.UWUserLanguageKey) UserDefaults.standard.set(nil, forKey: "AppleLanguages") UserDefaults.standard.synchronize()
}
}
class NSBundleEx: Bundle {
override func localizedString(forKey key: String, value: String?, table tableName:String?) -> String {
if let bundle = Bundle.getLanguageBundel() {
return bundle.localizedString(forKey: key, value: value, table: tableName)}else {
return super.localizedString(forKey: key, value: value, table: tableName)
}
}
}
extension Bundle{
private static var onLanguageDispatchOnce: ()->Void = {
//替换Bundle.main为自定义的BundleEx
object_setClass(Bundle.main, NSBundleEx.self)
}
func onLanguage(){
Bundle.onLanguageDispatchOnce()
}
class func getLanguageBundel() -> Bundle? {
let languageBundlePath = Bundle.main.path(forResource:DAConfig.getUserLanguage(), ofType: "lproj")
guard languageBundlePath != nil else {
return nil
}
let languageBundle = Bundle.init(path: languageBundlePath!)
guard languageBundle != nil else {
return nil
}
return languageBundle!
}
}
因为swift不允许重写load方法 所以我们用的是onLanguage(),需要在程序启动时调用它;
使用时如下:
if indexPath.row == 0 {
DAConfig.setUserLanguage(userLanguage: "zh-Hans")
}else{
DAConfig.setUserLanguage(userLanguage: "en")
}