Reputation: 1971
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()
}
}
Upvotes: 0
Views: 326
Reputation: 36782
For .pickerStyle(.navigationLink)
to work you need to have a NavigationStack
for example:
var body: some View {
NavigationStack {
VStack (alignment: .leading) {
....
Upvotes: 3