hitTest、pointInside

控制响应区域可以重写hitTest 或者 pointInside 方法


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    //系统默认会忽略isUserInteractionEnabled设置为NO、隐藏、alpha小于等于0.01的视图
    if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }
    if ([self pointInside:point withEvent:event]) {
        for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
            CGPoint convertedPoint = [subview convertPoint:point fromView:self];
            UIView *hitTestView = [subview hitTest:convertedPoint withEvent:event];
            if (hitTestView) {
                return hitTestView;
            }
        }
        return self;
    }
    return nil;
}


import UIKit

class HHButton: UIButton {

    var tapEndgeInsets: UIEdgeInsets = .zero
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if self.bounds.equalTo(self.enlargedRect()) {
            return super.point(inside: point, with: event)
        }else {
            if enlargedRect().contains(point) {
                return true
            }
            return false
        }
    }
    
    func enlargedRect() -> CGRect {
        return CGRect.init(x: self.bounds.origin.x - self.tapEndgeInsets.left, y: self.bounds.origin.y - self.tapEndgeInsets.right, width: self.bounds.size.width + self.tapEndgeInsets.left + self.tapEndgeInsets.right, height: self.bounds.size.height + self.tapEndgeInsets.top + self.tapEndgeInsets.bottom)
    }

}

你可能感兴趣的:(hitTest、pointInside)