2011-10-11 79 views
-1

我有一個UIButton,當點擊開始搜索數據。但是在搜索時,如果用戶再次點擊該按鈕,則取消搜索。如何在UIButton上按住雙按鈕取消操作?

相關代碼:

- (void)searchAction:(UIButton *)sender { 

    [sender removeTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside]; 
    [sender addTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside]; 
    [animatedImages startAnimating]; 
    //action that should be done 

} 

- (void)cancelSearch:(UIButton *)sender { 
    [sender removeTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside]; 
    [sender addTarget:self action:@selector(searchNearbyAction:) forControlEvents:UIControlEventTouchDown]; 
    [animatedImages stopAnimating]; 

} 

所以其基本思想是,當我點擊它,它的功能變化,取消和副verca

的問題是,當我點擊它的第一次它呼叫searchAction,然後無緣無故地致電cancelSearch

有誰知道爲什麼會發生這種情況?

+0

你有一個相當清晰的,寫得很好的解釋,但你的最後一行危及你的問題的質量。 「如果有人能解釋我發生了什麼,謝謝」並不是讓人們回答你的問題的好方法。試試這個,換一個新行: 「有誰知道爲什麼會發生這種情況?謝謝!」 – cincodenada

回答

5

一種解決方法是增加一個布爾作爲一個實例變量

BOOL canCancel; 

,然後執行以下

- (void)buttonClicked:(UIButton *)sender { 
     if (!canCancel) { 
      // action that should be done 
      canCancel = YES; 
     } else if (canCancel) { 
      // cancel action 
      canCancel = NO; 
     } 
} 
+0

感謝您的回覆。這是正確的方法嗎?我認爲將它們分開可能會更清潔。你有什麼想法解決我的問題嗎? –

+0

canCancel =!canCancel – thomax