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

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

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


当前回答

我试图为自己找出正确的解决办法。当我使用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
    }
}

其他回答

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)

在Swift中,有一个更简单的方法来获得当前应用程序语言:

Locale(identifier: Bundle.main.preferredLocalizations[0]).languageCode!

它可以像这样切换,例如:

let supportUrl: URL = {
    switch Locale(identifier: Bundle.main.preferredLocalizations[0]).languageCode {
    case "de":
        return Constants.supportUrlGerman

    default:
        return Constants.supportUrlEnglish
    }
}

我希望这能有所帮助!

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

将语言代码(如en_US)翻译成英语(United States)是NSLocale的内置特性,NSLocale并不关心你从哪里获得语言代码。因此,确实没有理由像公认的答案所建议的那样实现自己的翻译。

// Example code - try changing the language codes and see what happens
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSString *l1 = [locale displayNameForKey:NSLocaleIdentifier value:@"en"];
NSString *l2 = [locale displayNameForKey:NSLocaleIdentifier value:@"de"];
NSString *l3 = [locale displayNameForKey:NSLocaleIdentifier value:@"sv"];
NSLog(@"%@, %@, %@", l1, l2, l3);

印刷:英语,德语,瑞典语

I actually misread the original question, thought it asked for the "app UI" language (that's what I had googled for), not the "device UI", in which case the best answers would be the ones using preferredLocalizations, but those answers still give you a code, there is one more step to get a nice string to display. So, while the "device UI" language is already answered, if you want to display a nice string for which of the UI languages you support is currently in use, obviously the simplest solution is:

NSLocalizedString(@"currentLanguage", @"")

在你的每一个UI本地化中你都指定了你想要的显示方式。例如,在你的。strings文件的en版本中,你会有:

"currentLanguage"="English";

在你的fr版本的.strings文件中,你会有:

"currentLanguage"="Francais";

等。不要混淆代码等,你可以让你自己的字符串很好地匹配你的UI。