LocalizedStringResource didn't seem to work.
The .environment modifier may work on Views but not on the content of the view ( strings in the view used to build the shared content)
However, the localizedString method suggested by AI did work despite looking messy. A shame there's not a simpler solution.
@State var isOtherLanguage = false
var body: some View {
var myLocale: String { isOtherLanguage ? "de" : "en" }
VStack {
Toggle("Switch language", isOn: $isOtherLanguage).frame(maxWidth: 200)
HStack {
Text("❌\(myLocale): ")
Text(
LocalizedStringResource(
"Hello world!",
table: "Localizable",
locale: Locale(identifier: myLocale)
)
)
}
HStack {
Text("❌\(myLocale): ")
Text(
String(
localized: "Hello world!",
locale: (Locale(identifier: myLocale)),
comment: "To share"
)
)
.environment(\.locale, Locale(identifier: myLocale))
}
HStack {
Text("❌\(myLocale): ")
Text(localizedString)
}
HStack {
Text("✅\(myLocale): ")
Text("Hello world!")
.environment(\.locale, Locale(identifier: myLocale))
}
HStack {
Text("✅\(myLocale): ")
Text(localizedString("Hello world!", locale: myLocale))
}
}
}
func localizedString(_ key: String.LocalizationValue, locale: String) -> String {
guard let path = Bundle.main.path(forResource: locale, ofType: "lproj"),
let bundle = Bundle(path: path) else {
return String(localized: key)
}
return String(localized: key, bundle: bundle)
}