iOS判斷當(dāng)前點(diǎn)擊的位置是否在某個視圖上
記錄幾種判斷觸摸點(diǎn)是否在某個view上面的方法
-
第一種方式:
isDescendantOfView:通過
touch.view調(diào)用isDescendantOfView:方法,返回YES, 則觸摸點(diǎn)在我們需要判斷的視圖上;反之則不在。- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches.allObjects lastObject]; BOOL result = [touch.view isDescendantOfView:self.blueView]; NSLog(@"%@點(diǎn)擊在藍(lán)色視圖上", result ? @"是" : @"不是"); } -
第二種方式:
locationInView:和containsPoint結(jié)合使用- (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(@"%@點(diǎn)擊在藍(lán)色視圖上", result ? @"是" : @"不是"); } -
第三種方式:
locationInView:和CGRectContainsPoint結(jié)合使用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(@"這次%@點(diǎn)擊在藍(lán)色視圖上", result ? @"是" : @"不是"); } -
第四種方式:坐標(biāo)轉(zhuǎn)換convertPoint:fromLayer: 再判斷是否是在該視圖范圍內(nèi) 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(@"%@點(diǎn)擊在藍(lán)色視圖上", result ? @"是" : @"不是"); }