Can I programatically change the Localizable.strin

2019-08-26 22:25发布

I am creating an app which uses 2 languages Arabic and English. I have managed to change the layout to RTL for Arabic and normal for English. Also I have added the Localizable.strings file for Arabic and English.

The app picks up English and normal layout shows when English is selected and picks up Arabic and RTL layout is shown when the app is started the first time or on every restart.

It does not pick up Arabic or English Localizable.strings file on runtime. Is there a way to do this.

2条回答
闹够了就滚
2楼-- · 2019-08-26 23:12

Try following code...it might help you to come out from your problem.

Step 1

extension String {

    /// Returns the localized string value
    public var localized: String {
        if let bundleName:String = UserDefaults.standard.value(forKey: "USER_LANG") as? String {
            let path = Bundle.main.path(forResource: bundleName, ofType: "lproj")
            let bundle = Bundle.init(path: path!)
            return localize(withBundle: bundle!)
        } else {
            return localize(withBundle: Bundle.main)
        }

    }

    public func localize(withBundle bundle: Bundle) -> String
    {
        return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
    }

}

Step 2

  • Store the bundle name on a button click in user default.

Example

// Strore Base bundleName when english button is clicked
UserDefaults.standard.set("Base", forKey: "USER_LANG") 

// Strore fr(short from of french) bundleName when french button is clicked 
UserDefaults.standard.set("fr", forKey: "USER_LANG") 

Step 3

Usage

  • In String File

"lbl_name"="name";

// name will convert in French and English too
"lbl_name".localized

Thank you!!!

查看更多
狗以群分
3楼-- · 2019-08-26 23:20

You can change the current bundle you read from

extension String {
      func localizedStr(language:String) -> String {
          let path = Bundle.main.path(forResource: language, ofType: "lproj")
          let bundleName = Bundle(path: path!)
          return NSLocalizedString(self, tableName: nil, bundle: bundleName!, value: "", comment: "")

    }
}

In Action enter image description here enter image description here enter image description here

see demo here local

查看更多
登录 后发表回答