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()
}
}