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