I am using Picker with option for no selection, in iOS15 it is working fine, but in iOS16 it has a default value, how can I remove this default value, I don't need to show the text to the right of the Picker line when selection is nil.
struct ContentView: View {
@State private var selection: String?
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
List {
Section {
Picker("Strength", selection: $selection) {
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
}
}
}
}
}
in iOS15, when selection is nil, no text is displayed on the right side of the Picker row
but in iOS 16, the same code leads to different results, when selection is nil it has a default value
Xcode 14.1 Beta 3 logs: "Picker: the selection "nil" is invalid and does not have an associated tag, this will give undefined results."
To resolve this log you need to add an Option which uses the nil tag.
struct ContentView: View {
@State private var selection: String?
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
List {
Section {
Picker("Strength", selection: $selection) {
Text("No Option").tag(Optional<String>(nil))
ForEach(strengths, id: \.self) {
Text($0).tag(Optional($0))
}
}
Text("current selection: \(selection ?? "none")")
}
}
}
}
}