如何在 swiftUI 中选择项目时对选择器添加操作?
How do I add action on picker on selection of item in swiftUI?
我有一个带有特定项目列表(比如添加、编辑、删除)的选择器,在选择特定项目时,我需要移至另一个屏幕。我试过 onTapGuesture() 但是当我调试它时控制不会进入内部。
我找到了 3 种不同的方法来实现这一点。我拍的最后一张。所以,有这么多方法,你可以选择你想要的:
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[[=10=]]).tag([=10=])
}
}.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)
})
}
}
您将使用代码片段实现此目的:
我有一个带有特定项目列表(比如添加、编辑、删除)的选择器,在选择特定项目时,我需要移至另一个屏幕。我试过 onTapGuesture() 但是当我调试它时控制不会进入内部。
我找到了 3 种不同的方法来实现这一点。我拍的最后一张
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[[=10=]]).tag([=10=])
}
}.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)
})
}
}
您将使用代码片段实现此目的: