Mic*_*bro 5 gesture uitapgesturerecognizer swiftui
我在 SwiftUI 中有视图层次结构,例如
ParentView {
//other views
ChildView().highPriorityGesture(TapGesture().onEnded {
print("Tap!")
})
// other views
}self.gesture(tap)
Run Code Online (Sandbox Code Playgroud)
而且我想让父视图处理屏幕上的所有点击,尽管用户点击 ChildView 的情况。现在两个闭包都执行了。如何停止点击手势事件向上传播视图层次结构?
好吧,可能有一些具体的ChildView和ParentView,因为正如下面测试的(Xcode 11.2 / iOS 13.2)子视图手势只是覆盖父视图手势。
这是演示..点击黄色区域,然后点击绿色区域 - 没有混合回调
完整模块代码
import SwiftUI
struct TestGesturesPriority: View {
var body: some View {
VStack {
Text("Hello, World!")
.padding()
.background(Color.yellow)
.gesture(TapGesture().onEnded {
print(" -- child")
})
}
.frame(width: 400, height: 400)
.background(Color.green)
.gesture(TapGesture().onEnded {
print(">> parent")
})
}
}
Run Code Online (Sandbox Code Playgroud)
更新:变体List-Row
是的...列表(父级)-行(子级)案例显得非常具有挑战性...请找到下面的方法,它看起来很奇怪,但经过测试且有效
struct TestGesturesPriority: View {
let parentGesture = TapGesture().onEnded { // just for convenience
print(">> parent")
}
@GestureState private var captured = false
var body: some View {
List {
Text("Hello, World!").padding()
.background(Color.yellow)
.allowsHitTesting(true)
.gesture(DragGesture(minimumDistance: 0) // mimic Tap
.updating($captured, body: { (value, state, transaction) in
state = true // mark captured (will be reset automatically)
})
.onEnded { value in
// like Tap, but can be ignored if delta
// is large or out of view
print(" -- child")
}
)
}
.gesture(parentGesture, including: captured ? .subviews : .gesture)
}
}
Run Code Online (Sandbox Code Playgroud)
总结一下 - 实际上我认为这是另一个 List 缺陷