iOS开发之常用技术点iOS 常见问题

hitTest方法与PointInside

2019-03-28  本文已影响24人  越天高

hitTest

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

PointInside

    -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
        return YES;
    }

hitTest底层实现:

          if(self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) 
          return  nil;
         if(![self pointInside:point withEvent:event]) return nil;
int count = (int)self.subviews.count;
        for (int i = count - 1; i >= 0;i-- ) {
         UIView *childV = self.subviews[i];
       // 把当前坐标系上的点转换成子控件坐标系上的点.
        CGPoint childP = [self convertPoint:point toView:childV];
        判断自己的子控件是不是最适合的View
        UIView *fitView = [childV hitTest:childP withEvent:event];
        如果子控件是最适拿的View,直接返回
            if (fitView) {
                return  fitView;
            }
}

练习1

        -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
            判断当前点在不在按钮上.
            把当前点转换成按钮所在的坐标系
            CGPoint btnP = [self convertPoint:point toView:self.btn];
            if ([self.btn pointInside:btnP withEvent:event]) {
                return self.btn;
            }else{
               return [super hitTest:point withEvent:event];
            }
        }

练习2

        -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
            获取当前的手指
            UITouch *touch = [touches anyObject];
            获取当前手指所在的点
            CGPoint curP = [touch locationInView:self];
            获取当前手指的上一个点
            CGPoint preP = [touch previousLocationInView:self];
            计算X轴的偏移量
            CGFloat offsetX = curP.x - preP.x;
            计算Y轴的偏移量
            CGFloat offsetY = curP.y - preP.y; 
            修改按钮的形变,让按钮能够移动.   
            self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);    
        }
        -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
            把当前所在的点转换成按钮子控件上面的点
            CGPoint chatP =  [self convertPoint:point toView:self.chatBtn];
            判断转换后的点在不在按钮的控件上.
            if ([self.chatBtn pointInside:chatP withEvent:event]) {如果在
                直接返回,也就意味着,当前最适合的View,就是这个按钮
                return self.chatBtn;
            }else{如果不在,那么就保持系统原有做法.
              return  [super hitTest:point withEvent:event];
            }
        }
上一篇下一篇

猜你喜欢

热点阅读