重写hitTest的顶层UIView处理触摸后,能否将事件传递至下层视图?
当然可行!
你的需求完全可以实现,核心思路是先让顶层视图全权接收触摸事件(通过hitTest:始终返回自身),在完成自身逻辑处理后,手动将触摸事件转发给底层的目标视图——毕竟hitTest:是在触摸事件开始时就确定响应者的,无法在后续处理中动态调整,所以手动转发是更合适的方案。
下面是具体的实现步骤和注意事项:
关键实现步骤
- 保留现有
hitTest:逻辑:继续让顶层视图的hitTest:始终返回自身,确保所有触摸事件都先流入这个视图进行处理。 - 优先处理自身逻辑:在
touchesBegan:、touchesMoved:、touchesEnded:中先执行你的业务逻辑,比如判断是否需要转发事件的条件判断。 - 手动转发触摸事件:当确定需要传递事件给底层视图时,按以下流程操作:
- 将触摸点转换为底层视图坐标系下的位置(通常转换到
UIWindow或底层视图的父容器更准确)。 - 通过
hitTest:withEvent:在底层视图层级中找到真正需要响应触摸的目标视图。 - 调用目标视图对应的触摸方法,把事件完整传递过去。
- 将触摸点转换为底层视图坐标系下的位置(通常转换到
代码示例(Objective-C)
// 顶层视图的.h文件,声明一个开关控制是否转发事件 @property (nonatomic, assign) BOOL shouldForwardTouch; // 顶层视图的.m文件 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { // 保持现有逻辑,始终返回自身,确保触摸事件先到这里处理 return self; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 1. 先执行自身的触摸逻辑 [self handleCustomTouchStartLogic]; // 2. 判断是否需要转发事件 if (self.shouldForwardTouch) { UITouch *touch = touches.anyObject; // 将触摸点转换到window坐标系,方便在整个视图树中查找目标 CGPoint windowPoint = [touch locationInView:self.window]; // 假设底层视图都在self.superview中,也可以指定具体的容器视图 UIView *targetContainer = self.superview; UIView *targetView = [targetContainer hitTest:windowPoint withEvent:event]; // 确保目标视图不是自身且存在 if (targetView && targetView != self) { // 转发touchesBegan事件给目标视图 [targetView touchesBegan:touches withEvent:event]; } } } // 同理,在touchesMoved和touchesEnded中实现相同的转发逻辑 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self handleCustomTouchMoveLogic]; if (self.shouldForwardTouch) { UITouch *touch = touches.anyObject; CGPoint windowPoint = [touch locationInView:self.window]; UIView *targetContainer = self.superview; UIView *targetView = [targetContainer hitTest:windowPoint withEvent:event]; if (targetView && targetView != self) { [targetView touchesMoved:touches withEvent:event]; } } } - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self handleCustomTouchEndLogic]; if (self.shouldForwardTouch) { UITouch *touch = touches.anyObject; CGPoint windowPoint = [touch locationInView:self.window]; UIView *targetContainer = self.superview; UIView *targetView = [targetContainer hitTest:windowPoint withEvent:event]; if (targetView && targetView != self) { [targetView touchesEnded:touches withEvent:event]; } } } // 自定义逻辑示例 - (void)handleCustomTouchStartLogic { NSLog(@"顶层视图处理触摸开始事件"); }
重要注意事项
- 转发完整的触摸序列:一定要在
touchesBegan、touchesMoved、touchesEnded三个方法中都实现转发逻辑,否则底层视图可能因为只收到部分事件而出现状态异常(比如按钮按下后无法恢复正常状态)。 - 避免循环转发:务必判断目标视图不是顶层视图自身,防止出现事件循环的问题。
- 精准选择目标容器:如果底层视图有特定的父容器,直接用该容器调用
hitTest:会比用self.superview更精准,避免误触其他无关视图。 - 响应链的特殊处理:如果底层视图需要将事件继续向上传递到响应链(比如父视图或ViewController),直接调用
touchesXXX方法会让目标视图成为第一响应者,事件不会自动沿响应链传播;如果需要完整的响应链处理,可以考虑使用[[UIApplication sharedApplication] sendEvent:event],但这种方式要谨慎使用,避免干扰其他正常的事件处理流程。
内容的提问来源于stack exchange,提问作者user3560634
相关产品推荐
相关产品推荐

