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

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

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


当前回答

斯威夫特

获取设备的当前语言

NSLocale.preferredLanguages()[0] as String

获取应用程序语言

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

注意:

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

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

其他回答

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

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

甚至还有更好的方法来获取当前设备语言。让我们试试下面的代码-

NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);

这是阿比森的建议

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

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

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

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

iOS13, Swift 5+, WWDC2019 https://developer.apple.com/videos/play/wwdc2019/403/

用户可以独立于操作系统语言选择应用程序的首选语言。

你可以使用这些:

    // Returns a list of the user's preferred languages.
    // Maybe more than (or none of) your app supports!
    Locale.preferredLanguages

    // a subset of this bundle's localizations, re-ordered into the preferred order
    // for this process's current execution environment; the main bundle's preferred localizations
    // indicate the language (of text) the user is most likely seeing in the UI
    Bundle.main.preferredLocalizations



    // The current running app language
    Bundle.main.preferredLocalizations.first

    // list of language names this bundle appears to be localized to
    Bundle.main.localizations