I'm teaching myself SwiftUI, and have been generally impressed so far, but I've bumped into an issue with popovers that shows a gap in my understanding, and I've been unable to find a good solution to the issue (or information to help me further my understanding).
My goal is simple. I'd like to create a custom NumberPicker view which displays a number as plain text, but when clicked, puts up a pop-up which lets you select a new value from a provided list of values. (And, ideally, it would handle the case where selection = nil, displaying an empty string, but I can work on that bit later.)
I've got the basics in place, but my issue is that the selected value is not getting set back in the View's @Binding var after I make my selection.
I've included below a TestPicker that shows the problem (with helpful print() statements. With this View, no matter what value I select in the Preview Pane, the View's 'selection' var value doesn't change.
My question(s) are:
- What am I doing wrong? Have I just made a simple, newbie mistake?
- Can you offer pointers to good places to search when trying to work through problems such as this? Places with SwiftUI examples, etc.?
import SwiftUI
struct TestPicker: View {
@Binding var selection: Int
let range = 1...10
@State private var showPicker = false
var body: some View {
var _ = print("Initial selection: \(selection)")
Text("\(selection)")
.onTapGesture {
showPicker = true
}
.padding()
.popover(isPresented: $showPicker) { [$selection] in
VStack {
Picker("Select Number", selection: $selection ) {
ForEach(range, id: \.self) { num in
Text("\(num)").tag(num)
}
}
.pickerStyle(WheelPickerStyle())
.frame(width: 120, height: 200)
.onDisappear {
var _ = print("Picker.onDisappear() selection: \(selection)")
}
}
}
Divider()
Text("The selected value is \(selection)")
}
}
#Preview {
@State var myNum: Int = 8
return TestPicker(selection: $myNum)
}