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

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

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


当前回答

对于Swift 3.0,下面的代码可以用来回答你的问题:

 let language = Bundle.main.preferredLocalizations.first! as NSString

其他回答

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。

斯威夫特3

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

如果你只想得到语言,这里是我建议的答案:

NSString *langplusreg = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * langonly = [[langplusreg componentsSeparatedByString:@"-"] 
objectAtIndex:0];

在我的情况下,我只是想Locale语言而不是Locale区域。

输出: 如果你的区域语言是日语,区域区域是日本,那么:

朗加雷格 = 是-JP

朗只 = 和

提供的解决方案实际上会返回设备的当前区域——而不是当前选择的语言。这些通常是同一件事。但是,如果我在北美,我将我的语言设置为日语,我的区域仍然是英语(美国)。为了检索当前选择的语言,你可以这样做:

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的答案

-(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;

}