美文网首页
超出父视图的子视图如何响应点击事件

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

作者: sl泡泡龙 | 来源:发表于2017-02-24 12:17 被阅读37次

重写父视图的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

相关文章

网友评论

      本文标题:超出父视图的子视图如何响应点击事件

      本文链接:https://www.haomeiwen.com/subject/xsqwwttx.html