【轉自: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); }