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

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

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


当前回答

对于MonoTouch c#开发人员使用:

NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"

注:我知道这是一个iOS问题,但作为MonoTouch开发者,这个页面上的答案引导我走向正确的方向,我想分享一下结果。

其他回答

选择的答案返回当前设备语言,但不是应用程序中使用的实际语言。如果你没有在应用程序中为用户的首选语言提供本地化,则使用第一个可用的本地化,按用户的首选顺序排序。

要发现在本地化中选择的当前语言,请使用

[[NSBundle mainBundle] preferredLocalizations];

例子:

NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];

迅速:

let language = NSBundle.mainBundle().preferredLocalizations.first as NSString

对于获得用户设备当前语言使用以下它的代码,它为我工作。

NSString * myString = [[NSLocale preferredlanguage]objectAtIndex:0];

对于MonoTouch c#开发人员使用:

NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"

注:我知道这是一个iOS问题,但作为MonoTouch开发者,这个页面上的答案引导我走向正确的方向,我想分享一下结果。

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。

显然,解决方案依赖于,例如

[[NSLocale preferredLanguages] objectAtIndex:0]

通常工作正常,并返回当前设备语言。

但在某些情况下,它可能会产生误导:

如果你想要获取这个值的应用程序已经改变了语言,例如使用这样的代码:

NSString *lg = @"en"; // or anything like @"en", @"fr", etc.
[[NSUserDefaults standardUserDefaults] 
    setObject:[NSArray arrayWithObjects:lg, nil]  
    forKey:@"AppleLanguages"]

在这种情况下,[NSLocale preferredLanguages]实际上返回这个特定应用程序的首选语言集(和使用),而不是当前设备语言!

和…在这种情况下,正确获得实际当前设备语言(而不是之前在应用程序中设置的语言)的唯一方法是首先清除NSUserDefaults中的@"appleLanguages"键,像这样:

[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"AppleLanguages"];

然后,[NSLocale preferredLanguages]现在返回正确的值。

希望这对你有所帮助。