重写父控件中的方法:(两个方法任选其一:)
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
具体实现:
- 方法一:
//返回需要响应事件的view位置
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *view = [super hitTest:point withEvent:event];
if (view == nil) {
//转换坐标系
CGPoint newPoint = [self.thirdBtn convertPoint:point fromView:self];
//判断触摸点是否在button上
if (CGRectContainsPoint(self.thirdBtn.bounds, newPoint)) {
view = self.thirdBtn;
}
//NSLog(@"point:%@ : newPoint:%@",NSStringFromCGPoint(point),NSStringFromCGPoint(newPoint));
}
return view;
}
- 方法二:
//当point在父控件和子控件包含的区域时,应该返回YES,否则为NO;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
NSLog(@"point:%@",NSStringFromCGPoint(point));
if (!CGRectContainsPoint(self.bounds, point)) {
//转换坐标系
CGPoint newPoint = [self convertPoint:point toView:self.secondBtn];
//NSLog(@"newPoit:%@",NSStringFromCGPoint(newPoint));
//判断触摸点是否在secondBtn上
if (CGRectContainsPoint(self.secondBtn.bounds, newPoint)) {
return YES;
}
return NO;
}
return YES;
}
难点:
- 判断一个点是否在某个范围内
CGRectContainsPoint(Rect, Point); //判断Rect中是否包含Point
CGRectContainsRect(Rect1,Rect2);//判断Rect1中是否包含Rect2
- 实现对控制点坐标系的转换
`view1:视图一` `view2:视图二`
`point:view1坐标系中的点` `newPoint:新得到view2坐标系中的点`
//将point从view1的坐标系中转换到view2的坐标系中得到newPoint
CGPoint newPoint = [view2 convertPoint:point fromView:view1];
CGPoint newPoint = [view1 convertPoint:point toView:view2];
类似方法:
- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
- (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;