UIView hitTest的原理

【转自:http://blog.sina.com.cn/s/blog_59fb90df0101ab26.html

UIView 两个方法:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event

网上对这两个方法的讲解很多,但是大部分是纯文字的描述,我不再赘述,需要可以自己百度“UIView hitTest”等等。
我现在根据我的理解,把这两个方法的源码实现模拟出来。
注意:这里只是模拟,是为了让你更容易理解而已,距离真实的源码还有很大的差距,
比如里面的event我根本没用到。

- (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);
}

 

posted on 2014-10-17 17:13  没有什么能够阻挡  阅读(358)  评论(0编辑  收藏  举报

导航