子控件超过父控件点击范围

  • 封装控件层次太多,或子控件超过父控件区域,很容易出现点击没反应!

通用方案

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        for (UIView *subView in self.subviews) {
            CGPoint p = [subView convertPoint:point fromView:self];
            if (CGRectContainsPoint(subView.bounds, p)) {
                view = subView;
            }
        }
    }
    return view;
}


具体方案

/// 超出父控件点击范围
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { 
    CGPoint cartPoint = [self convertPoint:point toView:self.cartButton];
    if ([self.cartButton pointInside:cartPoint withEvent:event]) {
        return self.cartButton;
    } else {
        return [super hitTest:point withEvent:event];
    }
}
  • 关键:[self.cartButton pointInside:cartPoint withEvent:event]
    • 点在不在这个子控件self.cartButton上,不是self
    • 保证其它在self里的子控件也能正常点击


你可能感兴趣的:(子控件超过父控件点击范围)