iOS判斷當(dāng)前點(diǎn)擊的位置是否在某個視圖上的幾種方法

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 ? @"是" : @"不是");
    }
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容