iOS判斷當前點擊的位置是否在某個視圖上的幾種方法

轉自ericshen880412

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

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容