1 //触摸事件发生时寻找最合适的View,系统调用 hitTest: withEvent:方法找到最合适的View 2 //当前View发生触摸事件就会调用该方法 3 // hitTest: withEvent:方法的底层实现 4 - (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ 5 //判断触摸点是否在当前的View上,如果不在直接返回空 6 if (![self pointInside:point withEvent:event]) { 7 return nil; 8 } 9 //判断当前View是否能接收事件,不能接收事件的三种情况 10 if (self.userInteractionEnabled == NO || self.alpha <= 0.01 || self.hidden == YES) { 11 return nil; 12 } 13 //从后往前遍历子控件查找最合适的View 14 int count = (int) self.subviews.count; 15 for (int i = count -1; i >= 0; i--) { 16 //取出父控件View上的子控件 17 UIView *childV = self.subviews[i]; 18 //将父控件View上的点坐标进行转换 19 CGPoint chP = [self convertPoint:point toView:childV]; 20 //子控件再去查找最优View 21 UIView *fitV = [childV hitTest:chP withEvent:event]; 22 //如果子控件找到就返回最合适的View 23 if (fitV) { 24 return fitV; 25 } 26 } 27 //循环结束都没找到就返回当前View作为最合适的View 28 return self; 29 }
原文:http://www.cnblogs.com/JL-609/p/4960530.html