I'm new to SwiftUI, and my app also needs the feature translate language, so I have created a sample app first before incorporating this functionality to my other project. So as you can see in my code below, I can change the language by clicking the button, and it works flawlessly, but I have no idea how this would work with multiple views. I'm looking to localize all of them and want to remove redundancies.
import SwiftUI
struct ContentView: View {
@State var title = ""
var body: some View {
VStack{
Text(title)
.padding()
Button {
title = "welcomeTitle".localizableString("en")
} label: {
Text("EN")
}
Button {
title = "welcomeTitle".localizableString("ja")
} label: {
Text("JA")
}
}
.onAppear {
// title = "welcomeTitle".localizableString("en")
if(Bundle.main.preferredLocalizations.first == "ja"){
title = "welcomeTitle".localizableString("ja")
}
else{
title = "welcomeTitle".localizableString("en")
}
}
}
}
extension String {
func localizableString(_ name: String) -> String {
let path = Bundle.main.path(forResource: name, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
See before this
Then a convenient extension:
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
}
//For your button
Button {
//action
} label: {
Text("welcomeTitle".localized)
}
In your Localizable.strings file English, add the following: "welcomeTitle" = "welcomeTitle EN";
In your Localizable.strings file Japanese, add the following: "welcomeTitle" = "welcomeTitle JA";
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.