我想要显示设备UI使用的当前语言。我应该使用什么代码?
我想把它作为一个NSString完全拼写出来的格式。(@ en_US)
编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。
我想要显示设备UI使用的当前语言。我应该使用什么代码?
我想把它作为一个NSString完全拼写出来的格式。(@ en_US)
编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。
当前回答
斯威夫特3
let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)
其他回答
Swift 4的更新答案
let language = Bundle.main.preferredLocalizations.first
如果你正在寻找首选语言代码(“en”,“de”,“es”…),和本地化的首选语言名称(当前地区),这里有一个简单的Swift扩展:
extension Locale {
static var preferredLanguageIdentifier: String {
let id = Locale.preferredLanguages.first!
let comps = Locale.components(fromIdentifier: id)
return comps.values.first!
}
static var preferredLanguageLocalizedString: String {
let id = Locale.preferredLanguages.first!
return Locale.current.localizedString(forLanguageCode: id)!
}
}
iOS13, Swift 5+
Locale.preferredLanguages.first
iOS 9的解决方案:
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
language = "en-US"
NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];
languageDic将拥有所需的组件
NSString *countryCode = [languageDic objectForKey:@"kCFLocaleCountryCodeKey"];
countryCode = "US"
NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];
密码:
I actually misread the original question, thought it asked for the "app UI" language (that's what I had googled for), not the "device UI", in which case the best answers would be the ones using preferredLocalizations, but those answers still give you a code, there is one more step to get a nice string to display. So, while the "device UI" language is already answered, if you want to display a nice string for which of the UI languages you support is currently in use, obviously the simplest solution is:
NSLocalizedString(@"currentLanguage", @"")
在你的每一个UI本地化中你都指定了你想要的显示方式。例如,在你的。strings文件的en版本中,你会有:
"currentLanguage"="English";
在你的fr版本的.strings文件中,你会有:
"currentLanguage"="Francais";
等。不要混淆代码等,你可以让你自己的字符串很好地匹配你的UI。
-(NSString *)returnPreferredLanguage { //as written text
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSArray *preferredLanguages = [defaults objectForKey:@"AppleLanguages"];
NSString *preferredLanguageCode = [preferredLanguages objectAtIndex:0]; //preferred device language code
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"]; //language name will be in English (or whatever)
NSString *languageName = [enLocale displayNameForKey:NSLocaleIdentifier value:preferredLanguageCode]; //name of language, eg. "French"
return languageName;
}