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

源码 2024-10-6 03:59:04 7 0 来自 中国
iOS判定当前点击的位置是否在某个视图上
记载几种判定触摸点是否在某个view上面的方法
第一种方式:isDescendantOfView:

通过touch.view调用 isDescendantOfView:方法,返回 YES, 则触摸点在我们必要判定的视图上;反之则不在。
- (void)touchesBeganNSSet<UITouch *> *)touches withEventUIEvent *)event {     UITouch *touch = [touches.allObjects lastObject];    BOOL result = [touch.view isDescendantOfView:self.blueView];    NSLog(@"%@点击在蓝色视图上", result ? @"是" : @"不是");}第二种方式:locationInView:和 containsPoint 联合利用

- (void)touchesBeganNSSet<UITouch *> *)touches withEventUIEvent *)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,(即判定的是子视图,传入子视图的.bounds)。
- (void)touchesBeganNSSet<UITouch *> *)touches withEventUIEvent *)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)touchesBeganNSSet<UITouch *> *)touches withEventUIEvent *)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 ? @"是" : @"不是");}
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:47, Processed in 0.159817 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表