我想要显示设备UI使用的当前语言。我应该使用什么代码?
我想把它作为一个NSString完全拼写出来的格式。(@ en_US)
编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。
我想要显示设备UI使用的当前语言。我应该使用什么代码?
我想把它作为一个NSString完全拼写出来的格式。(@ en_US)
编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。
当前回答
对于MonoTouch c#开发人员使用:
NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"
注:我知道这是一个iOS问题,但作为MonoTouch开发者,这个页面上的答案引导我走向正确的方向,我想分享一下结果。
其他回答
iOS13, Swift 5+, WWDC2019 https://developer.apple.com/videos/play/wwdc2019/403/
用户可以独立于操作系统语言选择应用程序的首选语言。
你可以使用这些:
// Returns a list of the user's preferred languages.
// Maybe more than (or none of) your app supports!
Locale.preferredLanguages
// a subset of this bundle's localizations, re-ordered into the preferred order
// for this process's current execution environment; the main bundle's preferred localizations
// indicate the language (of text) the user is most likely seeing in the UI
Bundle.main.preferredLocalizations
// The current running app language
Bundle.main.preferredLocalizations.first
// list of language names this bundle appears to be localized to
Bundle.main.localizations
提供的解决方案实际上会返回设备的当前区域——而不是当前选择的语言。这些通常是同一件事。但是,如果我在北美,我将我的语言设置为日语,我的区域仍然是英语(美国)。为了检索当前选择的语言,你可以这样做:
NSString * language = [[NSLocale preferredLanguages] firstObject];
这将为当前选择的语言返回两个字母的代码。英语是“en”,西班牙语是“es”,德语是“de”,等等。更多例子,请参阅维基百科的条目(特别是639-1列):
ISO 639-1代码列表
然后,将这两个字母的代码转换为您想要显示的字符串就很简单了。如果是"en",显示"English"。
EDIT
值得引用NSLocale.h中的头信息:
+ (NSArray *)preferredLanguages NS_AVAILABLE(10_5, 2_0); // note that this list does not indicate what language the app is actually running in; the [NSBundle mainBundle] object determines that at launch and knows that information
对应用语言感兴趣的人可以看看@mindvision的答案
对于Swift 3.0,下面的代码可以用来回答你的问题:
let language = Bundle.main.preferredLocalizations.first! as NSString
从iOS 9开始,如果你只想要语言代码而不需要国家代码,你将需要这种帮助函数——因为语言将包含国家代码。
// gets the language code without country code in uppercase format, i.e. EN or DE
NSString* GetLanguageCode()
{
static dispatch_once_t onceToken;
static NSString* lang;
dispatch_once(&onceToken, ^
{
lang = [[[NSLocale preferredLanguages] objectAtIndex:0] uppercaseString];
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"^[A-Za-z]+" options:0 error:nil];
NSTextCheckingResult* match = [regex firstMatchInString:lang options:0 range:NSMakeRange(0, lang.length)];
if (match.range.location != NSNotFound)
{
lang = [lang substringToIndex:match.range.length];
}
});
return lang;
}
甚至还有更好的方法来获取当前设备语言。让我们试试下面的代码-
NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);
这是阿比森的建议