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

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

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


当前回答

将语言代码(如en_US)翻译成英语(United States)是NSLocale的内置特性,NSLocale并不关心你从哪里获得语言代码。因此,确实没有理由像公认的答案所建议的那样实现自己的翻译。

// Example code - try changing the language codes and see what happens
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSString *l1 = [locale displayNameForKey:NSLocaleIdentifier value:@"en"];
NSString *l2 = [locale displayNameForKey:NSLocaleIdentifier value:@"de"];
NSString *l3 = [locale displayNameForKey:NSLocaleIdentifier value:@"sv"];
NSLog(@"%@, %@, %@", l1, l2, l3);

印刷:英语,德语,瑞典语

其他回答

在Swift中,有一个更简单的方法来获得当前应用程序语言:

Locale(identifier: Bundle.main.preferredLocalizations[0]).languageCode!

它可以像这样切换,例如:

let supportUrl: URL = {
    switch Locale(identifier: Bundle.main.preferredLocalizations[0]).languageCode {
    case "de":
        return Constants.supportUrlGerman

    default:
        return Constants.supportUrlEnglish
    }
}

我希望这能有所帮助!

两封信的格式。苹果使用ISO标准ISO-3166。

NSString *localeCountryCode = [[NSLocale autoupdatingCurrentLocale] objectForKey:NSLocaleCountryCode];

斯威夫特

获取设备的当前语言

NSLocale.preferredLanguages()[0] as String

获取应用程序语言

NSBundle.mainBundle().preferredLocalizations[0] as NSString

注意:

它获取你在info.plist的CFBundleDevelopmentRegion中给出的语言

如果CFBundleAllowMixedLocalizations在info中为true。plist然后info中的cfbundlelocizations的第一项。返回Plist

对于Swift 3:

NSLocale。preferredLanguages[0]作为字符串

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

}