在父視圖重寫hitTest:withEvent:方法,代碼如下:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//CGRectMake(50, 50, 100, 100)是相對於該視圖而言的
if([self isLocationInRectWithPoint:point withRect:CGRectMake(50, 50, 100, 100)]){
for(UIView *subview in self.subviews){
if([self isLocationInRectWithPoint:point withRect:subview.frame]){
return subview;
}
}
return self;
}
return nil;
}
//判斷點是否在一個區域裏
- (BOOL)isLocationInRectWithPoint:(CGPoint)point withRect:(CGRect)rect {
if(point.x >= rect.origin.x && point.x <= rect.origin.x+rect.size.width
&& point.y >= rect.origin.y && point.y <= rect.origin.y+rect.size.height){
return YES;
}
return NO;
}
這時如果子視圖在父視圖區域之外也可以相應事件