简体   繁体   中英

How to change language manually runtime in swiftUI

I am new with Swift and SwiftUI. For my project I need multiple languages. I searched and found that i need the Strings file. I did that and everything worked except one thing, changing the language manually runtime. I tried several codes from other guys, but none of them worked. I have a settings view where you can change the language but nothing works. I would love to show you my previous code but I deleted it. Can someone tell me how to update the text in my views, keep in mind that im using SwiftUI.

First, you need to create a Localizable.string file in your project. Then put your translations there, for example

"key" = "value";

don't forget about the semicolon!!! when you have selected your localizable.string on the right sidebar click the localizable button. then you can use that translation in swiftUI by putting it in

Text("key")

is simple as that:) To add more languages in the left sidebar click on your project blueish icon then select your project and add more languages, before click finish on adding language be sure you have localize.string checkbox selected. Right near your Localizable.string you have a small arrow that means you have a new localizable file for another language.

to have posibility to change language during runtime we can extend String for example like that:

extension String {
    func localizedLanguage(language: String = "en") -> String {
        if let bundlePath = Bundle.main.path(forResource: language, ofType: "lproj") {
            if let bundle = Bundle(path: bundlePath) {
                return bundle.localizedString(forKey: self, value: self, table: nil)
            }
        }
    
        return self
    }
}

and then we can use it like that:

Text("WELCOME".localizedLanguage(language: "en"))

Of course, it's just a fast proof of concept, and we can write it better and add features like getting selected language from user defaults, data core, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM