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 ? @"是" : @"不是");
}