例如:在控制器view上添加一个橙色view,再添加一个透明度为0.9的蓝色view覆盖住橙色view
实现点击蓝色view时,如果触摸的点在橙色view范围内,则响应橙色view的点击事件
效果图如下:
image.png
布局为:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor;
OrangeView *sec = [OrangeView new];
sec.backgroundColor = UIColor.orangeColor;
sec.frame = CGRectMake(150, 150, 100, 100);
[self.view addSubview:sec];
UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(secTap)];
[sec addGestureRecognizer:tap2];
BlueView *fir = [BlueView new];
fir.backgroundColor = [UIColor hexColor:@"3275FD" alpha:0.9];
fir.frame = CGRectMake(100, 100, 200, 200);
[self.view addSubview:fir];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(firTap)];
[fir addGestureRecognizer:tap];
}
- (void)firTap{
NSLog(@"点击了蓝色");
}
- (void)secTap{
NSLog(@"点击了橙色");
}
蓝色view重写hitTest方法判断点是否在橙色view的rect范围
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView *hitView = [super hitTest:point withEvent:event];
//判断点是否在rect范围
//获取相对上层控件的rect
CGRect rect = CGRectMake(150-100, 150-100, 100, 100);
BOOL isRect = CGRectContainsPoint(rect, point);
if (isRect) {
return nil;
}else{
return hitView;
}
}
扩展:
判断rect1是否在rect2范围内
CGRectContainsRect(rect2, rect1);