是否可以处理触摸UIButton事件并将其传递给下一个响应者?
另一种有效的方法是重写UIResponder
类的touchesEnded:withEvent:
方法。
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// handle touch
[super touchesEnded:touches withEvent:event];
}
该方法的默认实现什么也不做。但是,
UIResponder
的直接 UIKit 子类,特别是UIView
,会将消息转发到响应者链上。 要将消息转发给下一个响应者,请将消息发送给super
(超类实现);不要直接将消息发送给下一个响应者。
为了确定视图层次结构中哪个UIView
应该接收触摸,使用方法-[UIView hitTest:withEvent:]
。根据文档:
此方法通过调用每个子视图的
pointInside:withEvent:
方法来遍历视图层次结构,以确定哪个子视图应该接收触摸事件。如果pointInside:withEvent:
返回YES
,则类似地遍历子视图的层次结构,直到找到包含指定点的最前面的视图。如果一个视图不包含该点,则忽略其视图层次结构的分支。
因此,一种方法是创建一个UIButton
子类并覆盖方法-pointInside:withEvent:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
if (CGRectContainsPoint(self.bounds, point) {
// The touch is within the button's bounds
}
return NO;
}
NO
将使命中测试失败,并将触摸沿视图层次结构传递。
touchesEnded
和touchesBegan
吗? - Gabriele Petronella