2016-11-14 162 views
0

在應用程序中,我創建了幾個動態按鈕並將其添加到UITableView,每個按鈕都有一個觸摸事件(UIControlEventTouchUpInside)和一個長按手勢(UILongPressGestureRecognizer),我希望一次執行任何一個動作。所以如果用戶觸摸時只有按鈕動作將被調用。如果用戶長時間按下,則長按事件將被調用。如何處理UIButton上的觸摸事件和手勢事件?

目前,即使我長時間按下按鈕,它總是會調用操作。

我應該怎麼處理這個事件?有什麼好的建議?

+0

重複:http://stackoverflow.com/questions/30859203/uibutton-with-single-press-and-long-press-events-swift – Frankie

+2

可能重複[與長按和Touchup裏面的UIbutton](http://stackoverflow.com/questions/6660282/uibutton-with-longpress-and-touchup-inside) –

回答

0

爲了不觸發這兩個你應該國旗的全局變量或標籤上的按鈕,所以在UIControlEventTouchUpInside目標可以過濾作用。

因此,讓我們假設您的UILongPressGestureRecognizer在發生火災時調用longPress,並在您的自定義單元格中初始化。 & UIControlEventTouchUpInside調用目標btnPressed

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]; 
[self.button addGestureRecognizer:longPress]; 
[self.button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside]; 

選擇通話時,您的自定義單元格內:

-(void)longPress:(UIButton*)btn 
{ 
    // Flag the button, 
    self.button.tag = 1; 

    // Do LongPress stuff. 

} 

按鈕的目標爲UIControlEventTouchUpInside

- (void)btnPressed:(id)sender { 

    UIButton *senderButton = sender; 

    if(senderButton.tag == 1) { 
     // Long press has been executed, set back the flag to 0 
     senderButton.tag = 0; 
    } else { 
     // Long press not executed 
     // Do the TouchUpInside stuff. 
    } 
} 
0

在泰伯維的cellForRowAtIndex使用此代碼:

[cell.btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside]; 

而且cellForRowAtIndex之外實現此方法。

-(void)btnPressed:(UIButton*)btn 
{ 
    //Do whatever 
} 
0

而對於長按使用此代碼

`UILongPressGestureRecognizer` *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]; 
    [cell.button addGestureRecognizer:longPress]; 

長按的方法是

-(void)longPress:(UIButton*)btn 
{ 
    //Do whatever 
} 
0

您可以在按鈕的動作事件中添加以下代碼。我已經完成了tableview中多個複選框的代碼。藉助此代碼,您可以獲得TableView記錄的IndexPath。我希望這對你有用。

- (IBAction)btnPressed:(UIButton *)sender { 

CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.tblView]; 
NSIndexPath *indexpath = [self.tblView indexPathForRowAtPoint:touchPoint]; 
NSLog(@"%ld",(long)indexpath.row); 
}