How to change the label of a Menu?

832 views Asked by At

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"):

screenshot

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

1

There are 1 answers

2
George On BEST ANSWER

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".