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

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

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


当前回答

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

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

其他回答

SWIFT-4

 // To get device default selected language. It will print like short name of zone. For english, en or spain, es.

let language = Bundle.main.preferredLocalizations.first! as NSString
print("device language",language)

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

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

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

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

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

Swift 4的更新答案

let language = Bundle.main.preferredLocalizations.first

我试图为自己找出正确的解决办法。当我使用Locale.preferredLanguages.first从你的应用程序设置返回首选语言。

如果你想从用户设备设置中了解语言,你应该使用下面的字符串:

斯威夫特3

let currentDeviceLanguage = Locale.current.languageCode
// Will return the optional String

要展开并使用,请看下面这行:

if let currentDeviceLanguage = Locale.current.languageCode {
    print("currentLanguage", currentDeviceLanguage)

    // For example
    if currentDeviceLanguage == "he" {
        UIView.appearance().semanticContentAttribute = .forceRightToLeft
    } else {
        UIView.appearance().semanticContentAttribute = .forceLeftToRight
    }
}