我在子视图上有一个子视图。两者都附加了touchUpInside
个侦听器。当用户按下孩子时,我希望孩子和父视图都响应此触摸事件。当用户仅按下父级时,我只希望触发父级侦听器。
我该怎么做?
我已经尝试在子视图中重写以下方法,但是在此处返回false会完全忽略该子事件。相反,如果我在子级中处理touch事件,则父级会忽略它。
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return false
}
答案 0 :(得分:1)
如果两个视图都有子类,则可以覆盖UIView touchesBegan方法。如果您调用超级touchesBegan
方法,那么当事件沿响应者链上行时,这应该会产生您想要的结果。 (即,如果用户点击子视图,则孩子和父母的触摸事件都会响应)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("TOUCHED")
}
答案 1 :(得分:1)
快速示例...
点击“ innerView”,您将看到两个“接触开始”的调试打印。点击“ outerView”,您只会看到一个。
class TouchView: UIView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("touches began in \(self)")
}
}
class TouchTestViewController: UIViewController {
let innerView: TouchView = {
let v = TouchView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .red
return v
}()
let outerView: TouchView = {
let v = TouchView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(outerView)
outerView.addSubview(innerView)
NSLayoutConstraint.activate([
outerView.widthAnchor.constraint(equalToConstant: 300),
outerView.heightAnchor.constraint(equalToConstant: 300),
outerView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
outerView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
innerView.widthAnchor.constraint(equalToConstant: 150),
innerView.heightAnchor.constraint(equalToConstant: 150),
innerView.centerXAnchor.constraint(equalTo: outerView.centerXAnchor),
innerView.centerYAnchor.constraint(equalTo: outerView.centerYAnchor),
])
}
}