问题
I have a picker with certain list of items (say- Add, Edit, Delete) and on selection on particular item, I need to move to a different screen. I tried onTapGuesture() but control does not go inside when I debug the same.
回答1:
I found 3 different ways to achieve this. The last one I took here. So, there are all these ways, you can choose which you want:
struct PickerOnChange: View {
private var options = ["add", "edit", "delete"]
@State private var selectedOption = 0
@State private var choosed = 0
var body: some View {
VStack {
Picker(selection: $selectedOption.onChange(changeViewWithThirdWay), label: Text("Choose action")) {
ForEach(0 ..< self.options.count) {
Text(self.options[$0]).tag($0)
}
}.pickerStyle(SegmentedPickerStyle())
// MARK: first way
VStack {
if selectedOption == 0 {
Text("add (first way)")
} else if selectedOption == 1 {
Text("edit (first way)")
} else {
Text("delete (first way)")
}
Divider()
// MARK: second way
ZStack {
AddView()
.opacity(selectedOption == 0 ? 1 : 0)
EditView()
.opacity(selectedOption == 1 ? 1 : 0)
DeleteView()
.opacity(selectedOption == 2 ? 1 : 0)
}
Divider()
// MARK: showing third way
Text("just to show, how to use third way: \(self.choosed)")
Spacer()
}
}
}
func changeViewWithThirdWay(_ newValue: Int) {
print("will change something in third way with: \(choosed), you can do everything in this function")
withAnimation {
choosed = newValue
}
}
}
// MARK: the third way
extension Binding {
func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
return Binding(
get: { self.wrappedValue },
set: { selection in
self.wrappedValue = selection
handler(selection)
})
}
}
You'll achieve this with code snippet:
来源:https://stackoverflow.com/questions/60490982/how-do-i-add-action-on-picker-on-selection-of-item-in-swiftui