如何在 Objective-C 中获取用户的语言环境?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1085506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:52:09  来源:igfitidea点击:

How to get language locale of the user in Objective-C?

objective-cmacoslocalization

提问by freddiefujiwara

I am developing an application for Mac OS X. I want to change indication contents by the language locale (English, Spanish, etc.) of the application user, how do I get information of which language is used?

我正在为 Mac OS X 开发应用程序。我想根据应用程序用户的语言环境(英语、西班牙语等)更改显示内容,如何获取使用哪种语言的信息?

回答by chaostheory

NSLog(@"localeIdentifier: %@", [[NSLocale currentLocale] localeIdentifier]);

回答by Chuck

You can use the NSLocale API to get that information, but it isn't necessary to do what you want to do. OS X has support for localizationbuilt into the OS — all you need to do is supply the appropriate language files and the user can select which language he wants.

您可以使用 NSLocale API 来获取该信息,但没有必要做您想做的事情。OS X支持内置于 OS 中的本地化——您需要做的就是提供适当的语言文件,用户可以选择他想要的语言。

回答by lenhhoxung

code snippet

代码片段

 NSLocale *locale = [NSLocale currentLocale]; 
 [locale objectForKey:NSLocaleLanguageCode]

回答by Mohamad Chami

you can use any way of both ways below:

您可以使用以下两种方式中的任何一种:

NSString *language = [[NSLocale currentLocale] localeIdentifier];
NSLog(@"Language: %@", language);

output: Language: en_US

输出:语言:en_US

or this:

或这个:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSLog(@"Language: %@", language);

output: Language: en

输出:语言:en

回答by Ben Gotow

You're looking to "localize" your application. To get started, check out the Apple docs here: Internationalization - Apple Developer Docs. Without knowing more about your specific application, it'd be hard to suggest anything more here!

您希望“本地化”您的应用程序。首先,请在此处查看 Apple 文档:国际化 - Apple 开发人员文档。如果不了解有关您的特定应用程序的更多信息,就很难在这里提出更多建议!

回答by chepiok

To be exact there is a change with iOS 9 and greater where [NSLocale preferredLanguages] now return - instead of only . So it's better to do:

确切地说,iOS 9 及更高版本发生了变化,其中 [NSLocale preferredLanguages] 现在返回 - 而不仅仅是 . 所以最好这样做:

NSString *languageOS = [[NSLocale preferredLanguages] objectAtIndex:0];

if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
    languageOS = [[languageOS componentsSeparatedByString:@"-"] objectAtIndex:0];
}