美文网首页
iOS 子控件超出父控件如何触发事件

iOS 子控件超出父控件如何触发事件

作者: MasterChen | 来源:发表于2016-10-27 20:17 被阅读0次

    重写父控件中的方法:(两个方法任选其一:)

        - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
        - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
    

    具体实现:

    1. 方法一:
      //返回需要响应事件的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;
      }
    2. 方法二:
      //当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;
      }

    难点:

    1. 判断一个点是否在某个范围内
    • CGRectContainsPoint(Rect, Point); //判断Rect中是否包含Point
    • CGRectContainsRect(Rect1,Rect2);//判断Rect1中是否包含Rect2
    1. 实现对控制点坐标系的转换
        `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;
    

    相关文章

      网友评论

          本文标题:iOS 子控件超出父控件如何触发事件

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