在 iOS 中以编程方式更改应用程序中的语言

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22061402/
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-08-30 23:35:29  来源:igfitidea点击:

Change Language in the app programmatically in iOS

iosxcodelocalization

提问by user3278013

How to change the language in Xcode 5

如何更改 Xcode 5 中的语言

I have 3 buttons on the ChangeLanguageViewController

我有 3 个按钮 ChangeLanguageViewController

This are:

这是:

  • English
  • Chinese Simplified
  • Bahasa Malaysia
  • 英语
  • 简体中文
  • 马来西亚语

Here is code:

这是代码:

#import <UIKit/UIKit.h>
@interface ChangeLanguageViewController :UIViewController
-(IBAction)changeEnglish:(id)sender;
-(IBAction)changeChinesesimplified:(id)sender;
-(IBAction)changeBahasaMalaysia:(id)sender;

-(IBAction)changeEnglish:(id)sender{

[[NSUSerDefaults standardUSerDefaults] setObject:[NSArray arrayWithObjects:@"en", @"zh-Hans", @"ms", nil] forKey:@"AppleLanguage"];
}
-(IBAction)changeChinesesimplified:(id)sender{
[[NSUSerDefaults standardUSerDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans", @"ms", @"en", nil] forKey:@"AppleLanguage"];
}
-(IBAction)changeBahasaMalaysia:(id)sender{
[[NSUSerDefaults standardUSerDefaults] setObject:[NSArray arrayWithObjects:@"ms",@"en",@"zh-Hans", nil] forKey:@"AppleLanguage"];
}

I want to see the language change when the user presses a button and it will not kill the application but it changes the language of the app inside

我想在用户按下按钮时看到语言的变化,它不会终止应用程序,但它会更改应用程序内部的语言

回答by frin

Usually when you support official languages that Apple supports in iOS, there is no reason to provide language switching within the app, just properly set up translations in your project and interface language will automatically switch with the system. But since you want it from the app, there are few ways to go about this:

通常当你在 iOS 中支持 Apple 支持的官方语言时,没有理由在 app 内提供语言切换,只需在你的项目中正确设置翻译,界面语言会自动随系统切换。但是由于您希望从应用程序中获得它,因此有几种方法可以解决此问题:

1) You could force a specific language for just your app with the following code:

1) 您可以使用以下代码为您的应用强制使用特定语言:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans", @"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

I would suggest putting this code inside main.m file in "int main" function just before the "return UIApplicationMain". But this method requires you to kill the app or tell user to restart the app for it to take effect.

我建议将此代码放在 main.m 文件中的“int main”函数中,就在“return UIApplicationMain”之前。但是这种方法需要你杀死应用程序或告诉用户重新启动应用程序才能生效。

You can kill the app without having user to force quit the app using exit(0), but make sure user has chance to abort the action with UIAlertViewor similar, or Apple might reject your app.

您可以在不让用户使用 强制退出应用程序的情况下exit(0)终止应用程序,但请确保用户有机会使用UIAlertView或类似方法中止操作,否则 Apple 可能会拒绝您的应用程序。

2) Alternative is implementing your own localization logic, where you just take translations from your own language file. One way is this examplewhich takes translations from official lproj files. This way you can change the language on the fly without a restart, but you have to manually load all label texts from the code. When you change the translation, you have to repopulate the text on screen.

2) 另一种方法是实现您自己的本地化逻辑,您只需从自己的语言文件中获取翻译。一种方法是这个例子,它从官方 lproj 文件中获取翻译。通过这种方式,您可以在不重启的情况下即时更改语言,但您必须从代码中手动加载所有标签文本。当您更改翻译时,您必须重新填充屏幕上的文本。

回答by Tarek Hallak

You can't do this without restarting the app. So you need to save the selected language in NSUserDefaultsand restart the app after putting below lines in your main.h.

如果不重新启动应用程序,您将无法执行此操作。因此,您需要将所选语言保存NSUserDefaultsmain.h.

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects: your_lang, nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

回答by Anish Parajuli ?

EDIT:SWIFT 3.

编辑:SWIFT 3。

Use this helper class for your requirement.

根据您的要求使用此帮助程序类。

    class LanguageManager: NSObject {


    var availableLocales = [CustomLocale]()
    static let sharedInstance = LanguageManager()
    var lprojBasePath = String()

    override fileprivate init() {

        super.init()
        let english = CustomLocale(languageCode: GlobalConstants.englishCode, countryCode: "gb", name: "United Kingdom")
        let finnish  = CustomLocale(languageCode: GlobalConstants.finnishLangCode, countryCode: "fi", name: "Finland")
        self.availableLocales = [english,finnish]
        self.lprojBasePath =  getSelectedLocale()
    }


    fileprivate func getSelectedLocale()->String{

        let lang = Locale.preferredLanguages//returns array of preferred languages
        let languageComponents: [String : String] = Locale.components(fromIdentifier: lang[0])
        if let languageCode: String = languageComponents["kCFLocaleLanguageCodeKey"]{

            for customlocale in availableLocales {

                if(customlocale.languageCode == languageCode){

                    return customlocale.languageCode!
                }
            }
        }
        return "en"
    }

    func getCurrentBundle()->Bundle{

        if let bundle = Bundle.main.path(forResource: lprojBasePath, ofType: "lproj"){

            return Bundle(path: bundle)!

        }else{

            fatalError("lproj files not found on project directory. /n Hint:Localize your strings file")
        }
    }

    func setLocale(_ langCode:String){

        UserDefaults.standard.set([langCode], forKey: "AppleLanguages")//replaces Locale.preferredLanguages
        UserDefaults.standard.synchronize()
        self.lprojBasePath =  getSelectedLocale()
    }
}


 class CustomLocale: NSObject {
    var name:String?
    var languageCode:String?
    var countryCode:String?

    init(languageCode: String,countryCode:String,name: String) {

        self.name = name
        self.languageCode = languageCode
        self.countryCode = countryCode

    }

}

I have made a demo project in github.

我在github做了一个演示项目。