【iOS】Button點擊事件被其父視圖點擊手勢UITapGestureRecognizer的屏蔽問題

前幾天在做項目的時候,遇到這個一個問題,在一個視圖也就是UIView上添加一個手勢,然後又在這個View上添加一個UIButton,然後給按鈕添加事件,運行項目的時候我發現,不管是點擊按鈕還是視圖上的別的地方執行的都是手勢所擁有的方法,後來到網上找才發現是手勢把按鈕的方法給屏蔽了,那怎麼解決了正確的方法是給手勢設置代理,然後在代理中進行判斷如果點擊事件是由Button執行的,那就不執行手勢,那麼系統會調用按鈕所擁有的方法。具體的如下:

<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="objc"><span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="objc">UIView* showListView=[[UIView alloc] initWithFrame:[[UIScreen mainScreen]  bounds]];  
UITapGestureRecognizer* showTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showGes:)];  
showTap.delegate=self;//設置代理  UITapGestureRecognizer的代理爲UITapGestureRecognizerDelegate
tapGesture.cancelsTouchesInView = NO;//爲NO時view的點擊手勢覆蓋子視圖響應,爲YES時view的點擊手勢對其所有子視圖無效
[showListView addGestureRecognizer:showTap];  
[showTap release];  
</pre><pre>
<span style="font-family: Arial, Helvetica, sans-serif;">//創建View上的button</span>

UIButton* btn=[UIButton buttonWithType:UIButtonTypeCustom];  
btn.frame=CGRectMake(100.0,200.0,100.0,35.0);  
[btn addTarget:self action:@selector(coverViewChoose:) forControlEvents:UIControlEventTouchUpInside];  
[showListView addSubView:btn];  

#pragma mark--UIGestureRecognizerDelegate  
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch  
{  
    if([touch.view isKindOfClass:[UIButton class]])  
    {  
        return NO;  
    }  
    return YES;  
} 


發佈了14 篇原創文章 · 獲贊 5 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章