我想要显示设备UI使用的当前语言。我应该使用什么代码?
我想把它作为一个NSString完全拼写出来的格式。(@ en_US)
编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。
我想要显示设备UI使用的当前语言。我应该使用什么代码?
我想把它作为一个NSString完全拼写出来的格式。(@ en_US)
编辑:对于那些开车路过的人来说,这里有大量有用的评论,因为随着新iOS版本的发布,答案也在不断变化。
当前回答
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。
其他回答
-(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;
}
这可能会给你你想要的:
NSLocale *locale = [NSLocale currentLocale];
NSString *language = [locale displayNameForKey:NSLocaleIdentifier
value:[locale localeIdentifier]];
它会在语言本身中显示语言的名称。 例如:
Français (France)
English (United States)
对于Swift 3:
NSLocale。preferredLanguages[0]作为字符串
@amir在Swift中的回应:
// Get language prefered by user
let langageRegion = NSLocale.preferredLanguages().first!
let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
let language = languageDic[NSLocaleLanguageCode]
对于MonoTouch c#开发人员使用:
NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"
注:我知道这是一个iOS问题,但作为MonoTouch开发者,这个页面上的答案引导我走向正确的方向,我想分享一下结果。