Swift : How to change language inside app?

前端 未结 6 1465
忘了有多久
忘了有多久 2020-12-31 19:31

i am using Localize-Swift library (Link) to localize my application and it works fine with .strings files. the problem is that i have to localize to a language

相关标签:
6条回答
  • 2020-12-31 19:53

    I think KababChi's answer was right. However, in the newer versions of Swift NSUserDefaults has been substituted by UserDefaults. So the code would look like this:

    UserDefaults.standard.set(languages[indexPath.row], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()
    

    App still needs to be restarted to apply these changes.

    0 讨论(0)
  • 2020-12-31 20:04

    found my answer :

    NSUserDefaults.standardUserDefaults().setObject(["language identifier"], forKey: "AppleLanguages") 
    NSUserDefaults.standardUserDefaults().synchronize()
    

    unfortunately user must restart the app! if anyone could find a solution to not restart the application please inform me.

    0 讨论(0)
  • 2020-12-31 20:04

    You can use NSBundle+Language third party class.

    0 讨论(0)
  • 2020-12-31 20:06

    In order to change the language without restarting your device you need to switch ‘lproj’ bundle.

    You can make it using this code:

    class L012Localizer: NSObject {
        class func DoTheSwizzling() {
            MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString(forKey:value:table:)), overrideSelector:
                #selector(Bundle.specialLocalizedString(key:value:table:)))
        }
    }
    
    extension Bundle {
        @objc func specialLocalizedString(key: String, value: String?, table tableName: String?) -> String {
            let currentLanguage = Localization.currentAppleLanguage()
            var bundle = Bundle();
            if let _path = Bundle.main.path(forResource: currentLanguage, ofType: "lproj") {
                bundle = Bundle(path: _path)!
            } else {
                let _path = Bundle.main.path(forResource: "Base", ofType: "lproj")!
                bundle = Bundle(path: _path)!
            }
            return (bundle.specialLocalizedString(key: key, value: value, table: tableName))
        }
    }
    
    func MethodSwizzleGivenClassName(cls: AnyClass, originalSelector: Selector, overrideSelector: Selector){
    
        let origMethod: Method = class_getInstanceMethod(cls, originalSelector)!;
        let overrideMethod: Method = class_getInstanceMethod(cls, overrideSelector)!;
        if (class_addMethod(cls, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
            class_replaceMethod(cls, overrideSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        } else {
            method_exchangeImplementations(origMethod, overrideMethod);
        }
    }
    

    Here we are exchanging the implementation of Bundle's localizedString method. Note: we exchanging the Implementation not the reference on the function.

    Now add this line in the Appdelegate in the didFinishLaunchingWithOptions delegate method.

    L102Localizer.DoTheSwizzling()
    

    After that you need to reload your ViewControllers. In your Main.storyboard set Root View Controller's StoryboardId to "rootnav" and paste this code to your method that switches language:

    let rootviewcontroller: UIWindow = ((UIApplication.shared.delegate?.window)!)!
    rootviewcontroller.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "rootNav")
    let mainwindow = (UIApplication.shared.delegate?.window!)!
    mainwindow.backgroundColor = UIColor(hue: 0.6477, saturation: 0.6314, brightness: 0.6077, alpha: 0.8)
    UIView.transition(with: mainwindow, duration: 0.55001, options: .transitionFlipFromLeft, animations: { () -> Void in
    }) { (finished) -> Void in
    }
    
    0 讨论(0)
  • 2020-12-31 20:08
    1. Requires restart of app. Follow below lines of code.

      UserDefaults.standard.set(["language identifier"], forKey: "AppleLanguages") UserDefaults.standard.synchronize()

    2. Restart of app not requires ( the answer may requires customization in provided source code). Follow the provided web link.

    http://www.factorialcomplexity.com/blog/2015/01/28/how-to-change-localization-internally-in-your-ios-application.html

    0 讨论(0)
  • 2020-12-31 20:13

    Maybe the RSMultiLanguage pod is something useful for you? I have used it in my apps and it provides to possibility to change the user language in app. I'm pretty sure you can set it depending on the user location with an if loop. That way you might not have to restart the app.

    RSMultiLanguage

    Usage

    To run the example project, clone the repo, and run pod install from the Example directory first.

    Installation

    RSMultiLanguage is available through CocoaPods. To install it, simply add the following line to your Podfile:

    pod "RSMultiLanguage"
    

    Author

    Roy Ng, roytornado@gmail.com

    License

    RSMultiLanguage is available under the MIT license. See the LICENSE file for more info.

    0 讨论(0)
提交回复
热议问题