1

I'm trying to build an app, from where user can select the language and i want to change the content of whole application. For example i have two labels and two languages english and german. two files of Localizable (en , de). on my screen user press turn to german and i want to change the language of the application and want to update the UI but i dont want to the user to close the application. I found some of solution over here but that didn't work out like similar question

extension Bundle {
private static var bundle: Bundle!

public static func localizedBundle() -> Bundle! {
    if bundle == nil {
        let appLang = UserDefaults.standard.string(forKey: "app_lang") ?? "ru"
        let path = Bundle.main.path(forResource: appLang, ofType: "lproj")
        bundle = Bundle(path: path!)
    }

    return bundle;
}

public static func setLanguage(lang: String) {
    UserDefaults.standard.set(lang, forKey: "app_lang")
    let path = Bundle.main.path(forResource: lang, ofType: "lproj")
    bundle = Bundle(path: path!)
}}

and this

extension String {
func localized() -> String {
    return NSLocalizedString(self, tableName: nil, bundle: Bundle.localizedBundle(), value: "", comment: "")
}

func localizeWithFormat(arguments: CVarArg...) -> String{
    return String(format: self.localized(), arguments: arguments)
}}

and using it like

@IBAction func englishAction(_ sender: Any) {
    let  localisedSt = "en".localized()
    Bundle.setLanguage(lang: "en")
}

after this i tried to reload app , reload view but nothing change.

Aqib Javed
  • 103
  • 13

1 Answers1

0

NSLocalizedString will look up inside the localization table appropriate for the application which is determined by device or UserDefaults. There is a custom key that you can set inside UserDefaults and determine what language you're wishing to use, then on the next launch of the application it will load the appropriate bundle.

If you want to change localization inside the application(on the fly), you need to lookup the table manually from Bundle representing that Locale. Just look for the file with extension .lproj and recreate another Bundle with fetched path, and query generated Bundle for localized string.

let locale = Locale(identifier: "en");
guard let path = Bundle.main.path(forResource: locale.identifier, ofType: "lproj") 
else { return };
let localizedBundle = Bundle(path: path)
localizedBundle.localizedString(forKey:_, value:_, table:_) // you can pass NULL in table to look into "Localizable.strings"

But of-course, after changing the locale, you also need to update all currently configured texts.

I wrote a library called Styled that can help you with that part (that and also Interpolation, Color/Font synchronization with device font system)

farzadshbfn
  • 2,710
  • 1
  • 18
  • 38