Switching Locale with Picker

I'm trying to change the locale of an app with Picker as follows.

import SwiftUI

@main
struct LocaleSwitchCrazyMamaApp: App {
    var body: some Scene {
        WindowGroup {
            let lanSetting = LanguageSetting()
            ContentView()
                .environmentObject(lanSetting)
                .environment(\.locale, lanSetting.locale)
        }
    }
}
class LanguageSetting: ObservableObject {
	@Published var locale = Locale(identifier: "en")
}
import SwiftUI

struct ContentView: View {
	@State private var segmentSelection = 0
	@EnvironmentObject var languageSetting: LanguageSetting
	
	var body: some View {
		VStack {
			Text(NSLocalizedString("Hello", comment: ""))
				.padding(.vertical, 20)
			Picker("Language", selection: $segmentSelection) {
				Text("English").tag(0)
				Text("Japanese").tag(1)
				Text("French").tag(2)
			}
			.frame(width: 200)
			.pickerStyle(.segmented)
			.onChange(of: segmentSelection) {newValue in
				if newValue == 0 {
					languageSetting.locale = Locale(identifier: "en")
				} else if newValue == 1 {
					languageSetting.locale = Locale(identifier: "ja")
				} else {
					languageSetting.locale = Locale(identifier: "fr")
				}
			}
		}
		.padding()
	}
}

In addition, I have three locale versions like the following

"Hello" = "Hello"; // en.lproj

"Hello" = "Bonjour"; //fr.lproj

"Hello" = "こんにちは"; // ja.lproj

As long as I run the app on a simulator, the language of the Hello text won't change when tap any of the segments. What am I doing wrong?

Muchos thankos

Add a Comment

Replies

I've made some change the App View as follows.

import SwiftUI

@main
struct LocaleSwitchCrazyMamaApp: App {
	@StateObject var lanSetting = LanguageSetting()
	
	var body: some Scene {
		WindowGroup {
			ContentView()
				.environmentObject(lanSetting)
				.environment(\.locale, lanSetting.locale)
		}
	}
}

The outcome doesn't change, though.