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

重写父视图的hitTest方法

#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

你可能感兴趣的:(超出父视图的子视图如何响应点击事件)