在appDelegate didFinishLaunchingWithOptions
中,我将值存储在UserDefaults
中,如下所示:
UserDefaults.standard.setValue("fr", forKey: "selectedLocale")
我有extension
String
UserDefaults
我访问nil
之前存储的值,但我得到了func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
。当我尝试调试代码时,我知道扩展程序在 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/*----------------- Setting Locale on App Launch ------------------*/
// UserDefaults.standard.setValue((UserDefaults.standard.value(forKey: "AppleLanguages") as! [Any])[0], forKey: USER_DEFAULT.selectedLocale)
let country = NSLocale.current
if let locale = country.collatorIdentifier {
if locale.contains("en") {
Singleton.sharedInstance.currentLocale = "en"
} else {
Singleton.sharedInstance.currentLocale = "fr"
}
} else {
Singleton.sharedInstance.currentLocale = "fr"
}
Singleton.sharedInstance.isRTL = false
UserDefaults.standard.setValue(Singleton.sharedInstance.currentLocale, forKey: USER_DEFAULT.selectedLocale)
}
任何人都可以解释为什么会这样吗?
提前完成
我的代码如下:
适用于appDelegate:
extension String {
var localized: String {
let locale = UserDefaults.standard.value(forKey: USER_DEFAULT.selectedLocale) as? String
if let path = Bundle.main.path(forResource: locale, ofType: "lproj") {
let bundle = Bundle(path: path)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
return self
}
}
对于扩展程序:
left
答案 0 :(得分:1)
extension String
会调用。在您的代码中currentLocale
。对于我的意见,您需要在extension
中创建函数,并在存储值时调用它。
UserDefaults.standard.setValue(Singleton.sharedInstance.currentLocale, forKey: USER_DEFAULT.selectedLocale)
Singleton.sharedInstance.currentLocale.loadNib() //function in extension
例如
extension String {
func loadNib() {
let locale = UserDefaults.standard.value(forKey: USER_DEFAULT.selectedLocale) as? String
if let path = Bundle.main.path(forResource: locale, ofType: "lproj") {
let bundle = Bundle(path: path)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
}