現(xiàn)在有一個問題,點擊黃色子視圖超出紅色視圖的區(qū)域的時候,事件沒有響應(yīng)。原因是事件傳遞默認是在紅色父視圖的坐標區(qū)域里面的,所以超出的部分不起作用。

image.png
解決問題的思路:重寫紅色父視圖的- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event方法,當超出區(qū)域的適合返回黃色子視圖。
@interface UIView2:UIView
@end
@implementation UIView2
@end
@interface UIView1:UIView
@end
@implementation UIView1
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
if (![self pointInside:point withEvent:event]) {
for (UIView *view in self.subviews) {
CGPoint view2Point = [self convertPoint:point toView:view];
if ([view isKindOfClass:[UIView2 class]]&&CGRectContainsPoint(view.frame, view2Point)) {
return view;
}
}
}
return [super hitTest:point withEvent:event];
}
@end
//////
UIView1 *view1 = [UIView1 new];
view1.frame = CGRectMake(50, 100, 100, 100);
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];
UIView2 *view2 = [UIView2 new];
view2.frame = CGRectMake(10, 50, 100, 100);
view2.backgroundColor = [UIColor yellowColor];
[view1 addSubview:view2];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
[view2 addGestureRecognizer:tap];
////
- (void)tap{
NSLog(@"點擊了黃色的view");
}