swiftuipickerswiftui-navigationlink

Picker with nil option, and PickerStyle .navigationLink


I'm struggling to get a SwiftUI Picker with a nil option to use the .pickerStyle(.navigationLink), where on iPhone, the selection options are listed on a separate view.

The code below works fine for the default picker view (.menu) but when I change to .pickerStyle(.navigationLink) moodier, things no longer work - I notice my "No country selected" text becomes disabled and it's now flush right without the Spacer() pushing things to the left. I am likely missing something obvious but not sure what. Thanks!

struct ContentView: View { @State private var countrySelection: String? = nil

let countries = ["Australia", "UK", "USA"]
let countriesAndFlags = ["Australia": "🇦🇺", "UK": "🇬🇧", "USA": "🇺🇸"]

var body: some View {
    VStack (alignment: .leading) {
        Text("Country:")
            .bold()
        HStack {
            Picker("", selection: $countrySelection) {
                Text("No country selected").tag(nil as String?)
                ForEach(countries, id: \.self) { country in
                    Text("\(countriesAndFlags[country] ?? "") \(country)").tag(country as String?)
                }
            }
            .pickerStyle(.menu) // change .menu to .navigationLink to show problem
            Spacer()
        }
    }
    .padding()
}

}


Solution

  • For .pickerStyle(.navigationLink) to work you need to have a NavigationStack for example:

    var body: some View {
       NavigationStack {  
          VStack (alignment: .leading) { 
           ....