天天看点

iOS开发~子视图超过父视图范围的事件响应问题

当按钮超过了父视图范围,点击是没有反应的。因为消息的传递是从最下层的父视图开始调用hittest方法。

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    return view;
}
           

当存在view时才会传递对应的event,现在点击了父视图以外的范围,自然返回的是nil。所以当子视图(比如按钮btn)因为一些原因超出了父视图范围,就要重写 hittest方法,让其返回对应的子视图,来接收事件。

<span style="font-family:FangSong_GB2312;font-size:18px;">- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        CGPoint tempoint = [yourBtn convertPoint:point fromView:self];
        if (CGRectContainsPoint(yourBtn.bounds, tempoint))
        {
            view = yourBtn;
        }
    }
    return view;
}</span>