重写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/