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

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

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


当前回答

根据苹果文档

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

其他回答

你可以使用NSLocale的displayNameForKey:value:方法:

// get a French locale instance
NSLocale *frLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];

// use it to get translated display names of fr_FR and en_US
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"]);
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"en_US"]);

这将打印出:

français (France)
anglais (États-Unis)

如果你为initWithLocaleIdentifier:和displayNameForKey:value:方法指定了相同的语言环境标识符,那么它会给你语言的本机名称。我发现,如果你删除国家代码,只使用fr和en,它也会从显示名称中省略国家(至少在Mac OS X上,不确定iOS)。

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

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

这是阿比森的建议

对于Swift 3:

NSLocale。preferredLanguages[0]作为字符串

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。

根据苹果文档

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