swiftuilocalizationswiftui-menu

How to change the label of a Menu?


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


Solution

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