本文介绍了iOS:如何在不重新启动应用程序的情况下以编程方式更改应用程序语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在设备语言上独立更改应用程序使用的语言时,在我关闭应用程序并重新启动它之前它不会生效.如何根据所选语言不要求重新启动应用程序以再次加载所有 nib 文件和 .strings 文件?
When I change the app used language independently on the device language it doesn't take effect until I close the app and restart it. How to not require app to be restarted for loading all nib files and .strings files again depending on the selected language?
我使用它在运行时更改语言:
I use this to change language at runtime:
NSArray* languages = [NSArray arrayWithObjects:@"ar", @"en", nil];
[[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];
推荐答案
这对我有用:斯威夫特 4:
This works for me :Swift 4 :
创建一个名为 BundleExtension.swift 的文件,并在其中添加以下代码 -
Create a file named BundleExtension.swift and add the following code to it -
var bundleKey: UInt8 = 0
class AnyLanguageBundle: Bundle {
override func localizedString(forKey key: String,
value: String?,
table tableName: String?) -> String {
guard let path = objc_getAssociatedObject(self, &bundleKey) as? String,
let bundle = Bundle(path: path) else {
return super.localizedString(forKey: key, value: value, table: tableName)
}
return bundle.localizedString(forKey: key, value: value, table: tableName)
}
}
extension Bundle {
class func setLanguage(_ language: String) {
defer {
object_setClass(Bundle.main, AnyLanguageBundle.self)
}
objc_setAssociatedObject(Bundle.main, &bundleKey, Bundle.main.path(forResource: language, ofType: "lproj"), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
现在,当您需要更改语言时,请调用此方法:
Now whenever you need to change the language call this method :
func languageButtonAction() {
// This is done so that network calls now have the Accept-Language as "hi" (Using Alamofire) Check if you can remove these
UserDefaults.standard.set(["hi"], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
// Update the language by swaping bundle
Bundle.setLanguage("hi")
// Done to reintantiate the storyboards instantly
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateInitialViewController()
}
这篇关于iOS:如何在不重新启动应用程序的情况下以编程方式更改应用程序语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!