how to change Application language on run time using Two Button in iphone SDK?

前端 未结 7 1323
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 06:30

i am building up a project in ios platform and want to use two language in this application and also want . the user can change the language on Runtime suppose we can ta

7条回答
  •  生来不讨喜
    2020-12-17 06:53

    SWIFT 2.0 version We can do this on run time without restarting the app in Swift 2.0 as follows

    Make a function within a class, lets say LanguageManager is the name of the class

    class LanguageManager
    {
    
        static let sharedInstance =  LanguageManager()
    
        //Make a function for Localization. Language Code is the one which we will be deciding on button click.
        func LocalizedLanguage(key:String,languageCode:String)->String{
    
            //Make sure you have Localizable bundles for specific languages.
            var path = NSBundle.mainBundle().pathForResource(languageCode, ofType: "lproj")
    
            //Check if the path is nil, make it as "" (empty path)
            path = (path != nil ? path:"")
    
            let languageBundle:NSBundle!
    
            if(NSFileManager.defaultManager().fileExistsAtPath(path!)){
                languageBundle = NSBundle(path: path!)
                return languageBundle!.localizedStringForKey(key, value: "", table: nil)
            }else{
                // If path not found, make English as default
                path = NSBundle.mainBundle().pathForResource("en", ofType: "lproj")
                languageBundle = NSBundle(path: path!)
               return languageBundle!.localizedStringForKey(key, value: "", table: nil)
            }
        }
    }
    

    How to Use this.
    Now Assume you have two Languages for the application (English and Spanish)
    English - en
    Spanish - es

    Suppose you have to place something for a label

    //LOGIN_LABEL_KEY is the one that you will define in Localizable.strings for Login label text
     logInLabel.text = LanguageManager.sharedInstance.LocalizedLanguage("LOGIN_LABEL_KEY", languageCode: "es")
    
    //This will use the Spanish version of the text. 
    //"es" is the language code which I have hardcoded here. We can use a variable or some stored value in UserDefaults which will change on Button Click and will be passed in loginLabel
    

    For more info on language codes see this link below
    https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPInternational/LanguageandLocaleIDs/LanguageandLocaleIDs.html

    or

    http://www.ibabbleon.com/iOS-Language-Codes-ISO-639.html

提交回复
热议问题