In a simple test project at Github I am trying to display a Menu with 3 languages and the flags to allow users select the localization:
struct ContentView: View {
// ...some Core Data related code skipped...
let labels = [
"en" : " EN",
"de" : " DE",
"ru" : " RU"
]
@AppStorage("language") var language:String = "en"
var body: some View {
VStack(alignment: .trailing) {
Menu(language) {
Button(" EN", action: { language = "en" })
Button(" DE", action: { language = "de" })
Button(" RU", action: { language = "ru" })
}.padding()
List {
ForEach(topEntities) { top in
TopRow(topEntity: top)
}
}
}.environment(\.locale, .init(identifier: language))
}
}
The above code seems to work ok, but has one cosmetic problem: the Menu displays the selected language a simple string "en" (or "de", or "ru"):
Being a Swift and SwiftUI newbie I do not understand, how to set the label to the nicer string, i.e. to the selected language and flag, like " EN". Please help
You can get the nice string from your
labels
dictionary. Here is the working version:I just replaced
language
withlabels[language] ?? "Unknown"
.