我想要显示设备UI使用的当前语言。我应该使用什么代码?

我想把它作为一个NSString完全拼写出来的格式。(@ en_US)

编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。


当前回答

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"];

密码:

其他回答

根据苹果文档

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

甚至还有更好的方法来获取当前设备语言。让我们试试下面的代码-

NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);

这是阿比森的建议

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"];

密码:

对于Swift 3:

NSLocale。preferredLanguages[0]作为字符串

斯威夫特3

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)