代码改变世界

超出父视图的view如何响应点击事件

2021-04-23 17:04  菜鸟Alex  阅读(176)  评论(0编辑  收藏  举报

重写hit test方法

#import "RedView.h"
 
@interface RedView()
 
@property (nonatomic, strong) UIButton *greenView;
 
@end
 
@implementation RedView
 
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.greenView = [[UIButton alloc] initWithFrame:CGRectMake(75, -25, 50, 50)];
        self.greenView.backgroundColor = [UIColor greenColor];
        [self.greenView addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.greenView];
        
    }
    
    return self;
}
 
- (void)click {
    NSLog(@"click!!");
}
 
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        CGPoint temPoint = [self.greenView convertPoint:point fromView:self];
        if (CGRectContainsPoint(self.greenView.bounds, temPoint)) {
            view = self.greenView;
        }
    }
    return view;
}
 
@end

参考:
https://www.programmersought.com/article/7158812427/