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

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

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


当前回答

斯威夫特3

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?
print(code!)

其他回答

选择的答案返回当前设备语言,但不是应用程序中使用的实际语言。如果你没有在应用程序中为用户的首选语言提供本地化,则使用第一个可用的本地化,按用户的首选顺序排序。

要发现在本地化中选择的当前语言,请使用

[[NSBundle mainBundle] preferredLocalizations];

例子:

NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];

迅速:

let language = NSBundle.mainBundle().preferredLocalizations.first as NSString

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

快5.倍 我们可以使用设备语言 但是它会返回en表示英文,zh表示简体中文,zh表示繁体中文

事实上,如果我们能得到这样的东西会更有帮助。 zh-Hans表示简体中文 zh-Hant代表中文-繁体

这里zh是语言代码,Hans是scriptCode。

解决方案:

本地扩展( 统计var首选语言代码:[字符串] 地方preferredLanguages compactMap。( 如果脚本代码=本地(标识符:$0)。 let languageCode =本地(标识符:$0)。languageCode ( 返回语言+ - +脚本代码 ) 返回本地(id: $0) ) ) ) For example:[“zh-Hant”、“”、“zh-Hans”、“ko”、“ja”、“es”、“德”、“n”、“”、“it”)

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

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

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"];

密码: