扩大view点击范围的原理就是iOS的事件传递原理
事件从Window 上开始传递流程,
首先执行window的hottest with event 方法,
然后在该方法中会调用point inside 方法,判断点击点是否在
window中,如果在window中,再从下到上依次遍历window的子视图,并调用子视图的hittest with event 方法,并在hittest event 方法中调用自己的point inside 方法,依次递归,直到找到最上面的子视图为止
根据上面的事件传递原理,我们知道,如果我们想扩大一个试图的点击范围,就可以重写其)pointInside:(CGPoint)point withEvent 方法,在需要的范围内都返回YES
代码示例
自定义视图的.m文件
//扩大点击范围
- (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);
}
总结:我们要扩大谁的点击范围,就重写谁的pointInside withEvent 方法
前提是点击的范围必须要在父视图的范围内,因为在父视图的hittest 方法中,如果
在父视图的范围内,就会执行所有子视图的hittest 方法