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:
Menu(labels[language] ?? "Unknown") {
Button("πΊπΈ EN", action: { language = "en" })
Button("π©πͺ DE", action: { language = "de" })
Button("π·πΊ RU", action: { language = "ru" })
}.padding()
I just replaced language
with labels[language] ?? "Unknown"
.