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

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

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


当前回答

从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;
}

其他回答

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

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

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

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

朗加雷格 = 是-JP

朗只 = 和

斯威夫特

获取设备的当前语言

NSLocale.preferredLanguages()[0] as String

获取应用程序语言

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

注意:

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

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

迅速:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String

这可能会给你你想要的:

NSLocale *locale = [NSLocale currentLocale];

NSString *language = [locale displayNameForKey:NSLocaleIdentifier 
                                         value:[locale localeIdentifier]];

它会在语言本身中显示语言的名称。 例如:

Français (France)
English (United States)

iOS13, Swift 5+

Locale.preferredLanguages.first

iOS 9的解决方案:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

language = "en-US"

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic将拥有所需的组件

NSString *countryCode = [languageDic objectForKey:@"kCFLocaleCountryCodeKey"];

countryCode = "US"

NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];

密码: