美文网首页
iOS判断当前点击的位置是否在某个视图上的几种方法

iOS判断当前点击的位置是否在某个视图上的几种方法

作者: CoderGuogt | 来源:发表于2020-03-14 16:33 被阅读0次

iOS判断当前点击的位置是否在某个视图上

记录几种判断触摸点是否在某个view上面的方法

  • 第一种方式:isDescendantOfView:

    通过touch.view调用 isDescendantOfView: 方法,返回 YES, 则触摸点在我们需要判断的视图上;反之则不在。

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches.allObjects lastObject];
        BOOL result = [touch.view isDescendantOfView:self.blueView];
        NSLog(@"%@点击在蓝色视图上", result ? @"是" : @"不是");
    }
    
    
  • 第二种方式:locationInView:containsPoint 结合使用

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches.allObjects lastObject];
        CGPoint point = [touch locationInView:self.blueView];
        BOOL result = [self.blueView.layer containsPoint:point];
        NSLog(@"%@点击在蓝色视图上", result ? @"是" : @"不是");
    }
    
  • 第三种方式:locationInView:CGRectContainsPoint 结合使用

    locationView 如果传入的是需要判断视图(self.blueView)的父视图,CGRectContainsPoint则需要传入需要判断视图(self.blueView)frame,否则传入 bounds.

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {   
    
        UITouch *touch = [touches.allObjects lastObject];
        CGPoint point = [touch locationInView:self.blueView];
        BOOL result = CGRectContainsPoint(self.blueView.bounds, point);
        NSLog(@"这次%@点击在蓝色视图上", result ? @"是" : @"不是");
    }
    
  • 第四种方式:坐标转换convertPoint:fromLayer: 再判断是否是在该视图范围内 containsPoint:

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {   
    
        CGPoint point = [[touches anyObject] locationInView:self.view];
        point = [self.blueView.layer convertPoint:point fromLayer:self.view.layer];
        BOOL result = [self.blueView.layer containsPoint:point];
        NSLog(@"%@点击在蓝色视图上", result ? @"是" : @"不是");
    }
    

相关文章

网友评论

      本文标题:iOS判断当前点击的位置是否在某个视图上的几种方法

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