我在SwiftUI中有视图层次结构,比如
ParentView {
//other views
ChildView().highPriorityGesture(TapGesture().onEnded {
print("Tap!")
})
// other views
}self.gesture(tap)我想让父视图处理屏幕上的所有点击,尽管用户在ChildView上点击的情况下。现在两个闭包都执行了。如何停止点击手势事件向上传播视图层次结构?
发布于 2020-01-28 18:35:02
好吧,可能有一些具体的ChildView和ParentView,因为正如下面(Xcode11.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")
})
}
}更新:适用于List-Row的变体
是啊。List (Parent) - Row (Child)案例看起来非常具有挑战性...请找到下面的方法,它看起来很奇怪,但测试和工作
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)
}
}总而言之--实际上我认为这是另一个列表缺陷
https://stackoverflow.com/questions/59946147
复制相似问题