子視圖超出父視圖的部分視圖響應(yīng)事件的問題

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容