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

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

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


当前回答

快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”)

其他回答

对于Swift 3:

NSLocale。preferredLanguages[0]作为字符串

显然,解决方案依赖于,例如

[[NSLocale preferredLanguages] objectAtIndex:0]

通常工作正常,并返回当前设备语言。

但在某些情况下,它可能会产生误导:

如果你想要获取这个值的应用程序已经改变了语言,例如使用这样的代码:

NSString *lg = @"en"; // or anything like @"en", @"fr", etc.
[[NSUserDefaults standardUserDefaults] 
    setObject:[NSArray arrayWithObjects:lg, nil]  
    forKey:@"AppleLanguages"]

在这种情况下,[NSLocale preferredLanguages]实际上返回这个特定应用程序的首选语言集(和使用),而不是当前设备语言!

和…在这种情况下,正确获得实际当前设备语言(而不是之前在应用程序中设置的语言)的唯一方法是首先清除NSUserDefaults中的@"appleLanguages"键,像这样:

[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"AppleLanguages"];

然后,[NSLocale preferredLanguages]现在返回正确的值。

希望这对你有所帮助。

你可以使用NSLocale的displayNameForKey:value:方法:

// get a French locale instance
NSLocale *frLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];

// use it to get translated display names of fr_FR and en_US
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"]);
NSLog(@"%@", [frLocale displayNameForKey:NSLocaleIdentifier value:@"en_US"]);

这将打印出:

français (France)
anglais (États-Unis)

如果你为initWithLocaleIdentifier:和displayNameForKey:value:方法指定了相同的语言环境标识符,那么它会给你语言的本机名称。我发现,如果你删除国家代码,只使用fr和en,它也会从显示名称中省略国家(至少在Mac OS X上,不确定iOS)。

根据苹果文档

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

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