ios – SwiftUI – Reload views when language changes


In my app the user can change the language using a picker, and this selected language gets stored to UserDefaults.

Then, in the SwiftUI Views, I’m using this method to get the localized strings translated:

public static func localizedBasedSelectedLanguage(key: String, bundle: Bundle =  Bundle.main) -> String? {
    // Get the correct language bundle
    let bundlePath = bundle.path(forResource: locale.identifier, ofType: "lproj")!
    let bundle = Bundle(path: bPath)!

    // Return the translated string using the language bundle.
    return bundle.localizedString(forKey: key, value: "", table: nil)
}

The problem I have is when the user change the language, the screens remain localized in the old language until they are refreshed.

I have been able to force the screen to refresh by adding a reference to the AppStorage:

    @AppStorage("localIdentifier") private var localIdentifier: String = ""

And adding an empty onChange:

.onChange(of: localIdentifier) { _ in
    // Adding this forces the screen to reload when the localIdentifier changes
}

However, in order for this to work properly, this AppStorage and onChange need to be added to all the screens, which is quite annoying.

Is there a better way to force all screens to reload when the language changes?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img