首页 > 解决方案 > 响应孩子和父母的触摸事件

问题描述

我有一个分层在父视图上的子视图。两者都有touchUpInside听众。当用户按下孩子时,我希望孩子和父视图都响应这个触摸事件。当用户只按下父级时,我只想触发父级侦听器。

我该怎么做呢?

我尝试在我的子视图中覆盖以下方法,但在这里返回 false 完全忽略了子事件。相反,如果我在子级中处理触摸事件,则父级会忽略它。

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return false
    }

标签: iosswiftuiviewontouchlistenerevent-bubbling

解决方案


如果您有两个视图的子类,则可以覆盖UIView touchesBegan方法。如果您调用 supertouchesBegan方法,那么当事件沿响应者链向上传播时,这应该会产生您所追求的结果。(即如果用户点击子视图,子视图和父视图的触摸事件都会响应)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    print("TOUCHED")
}

推荐阅读