The principle of iOS expanding the click range of UIView

The principle of expanding the view click range is the event delivery principle of iOS

The event transfer process starts from the Window.
First, execute the hottest with event method of the window,
and then call the point inside method in this method to determine whether the clicked point is in
the window. If it is in the window, it traverses the window from bottom to top. Subview, and call the hittest with event method of the subview, and call your own point inside method in the hittest event method, recursively until the top subview is found

According to the above event delivery principle, we know that if we want to expand the click range of an attempt, we can rewrite its)pointInside:(CGPoint)point withEvent method, and return YES within the required range

code example

.m file for custom view

//扩大点击范围
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat top = 0;
    CGFloat left = 0;
    CGFloat bottom = 0;
    CGFloat right = 0;

    top = self.config.expandHitEdges.top;
    left = self.config.expandHitEdges.left;
    right = self.config.expandHitEdges.right;
    bottom = self.config.expandHitEdges.bottom;
    //添加负号使相应的内边距变为向外扩展
    UIEdgeInsets hitExpandEdge = UIEdgeInsetsMake(- top, - left, - bottom, -right);
    if(UIEdgeInsetsEqualToEdgeInsets(hitExpandEdge, UIEdgeInsetsZero) || !self.userInteractionEnabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitExpandEdge);
    return CGRectContainsPoint(hitFrame, point);
}

Summary: Whoever we want to expand the click range, rewrite whose pointInside withEvent method

The premise is that the scope of the click must be within the scope of the parent view, because in the hittest method of the parent view, if it is
within the scope of the parent view, the hittest methods of all subviews will be executed

Guess you like

Origin blog.csdn.net/LIUXIAOXIAOBO/article/details/130141058