【转自:http://blog.sina.com.cn/s/blog_59fb90df0101ab26.html】html
UIView 两个方法:ide
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
网上对这两个方法的讲解不少,可是大部分是纯文字的描述,我再也不赘述,须要能够本身百度“UIView hitTest”等等。
我如今根据个人理解,把这两个方法的源码实现模拟出来。
注意:这里只是模拟,是为了让你更容易理解而已,距离真实的源码还有很大的差距,
好比里面的event我根本没用到。
spa
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ UIView *touchView = self; if ([self pointInside:point withEvent:event]) { for (UIView *subView in self.subviews) { //注意,这里有坐标转换,将point点转换到subview中,好好理解下 CGPoint subPoint = CGPointMake(point.x - subView.frame.origin.x, point.y - subView.frame.origin.y); UIView *subTouchView = [subView hitTest:subPoint withEvent:event]; if (subTouchView) { //找到touch事件对应的view,中止遍历 touchView = subTouchView; break; } } }else{ //此点不在该View中,那么连遍历也省了,直接返回nil touchView = nil; } return touchView; } - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{ return CGRectContainsPoint(self.bounds, point); }