在父视图重写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;
}
这时如果子视图在父视图区域之外也可以相应事件