如何在swiftUI中选择项目时对选择器添加操作? [英] How do I add action on picker on selection of item in swiftUI?
本文介绍了如何在swiftUI中选择项目时对选择器添加操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有特定项目列表的选择器(例如-添加,编辑,删除),并且在选择特定项目时,我需要移至另一个屏幕.我尝试了onTapGuesture(),但在调试相同控件时并没有进入控件内部.
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.
推荐答案
我发现了3种不同的方法来实现这一目标.我在此处拿到的最后一个.因此,有所有这些方法,您可以选择所需的方法:
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:
这篇关于如何在swiftUI中选择项目时对选择器添加操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文