超出父檢視的子檢視如何響應點選事件

weixin_34146805發表於2017-02-24

重寫父檢視的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

相關文章