2012-01-09 232 views
5

我試圖改變行動對於UIButton的iOS中應用。我下面的代碼是否可以更改UIButton的操作?

button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

    [button addTarget:self action:@selector(aMethodShow:) forControlEvents:UIControlEventTouchDown]; 

    [button setTitle:@"Show View" forState:UIControlStateNormal]; 

    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 

    [view addSubview:button]; 

特別是部分我想改變操作此按鈕。所以我這樣做

[button addTarget:self action:@selector(aMethodHide:) forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Hide View" forState:UIControlStateNormal]; 

遺憾的是此代碼備註工作?

+0

aMethodShow工作首次? aMethodHide在你改變它時不工作? – 2012-01-09 06:20:21

+0

兩個動作都採取相同的事件(點擊)的按鈕,我如何刪除第一個目標。 – 2012-01-09 06:39:10

+0

你的意思是說,當你點擊時,兩個方法都被調用? – 2012-01-09 06:41:03

回答

17

我建議在添加新目標之前,首先調用removeTargetUIbutton對象,然後用其他動作添加新目標。

+0

它的工作好,爲什麼這個動作調用相同的事件 – 2012-01-09 06:47:25

2

您可以使用相同的操作目標,而不是使用兩個目標。在一個目標,你必須區分像下面

-(void)btnAction 
{ 
     if(target1) 
      { 
      // code for target 1 
      } 

     else 
     { 
      // code for target 2 
     } 

} 

這裏是目標1 BOOL值值首先設置爲YES。每當你想執行目標2代碼時,改變它的值NO

我希望這將幫助你。

+0

如果我不想檢查的條件,如果我設置目標不止一次與不同的選擇器(showButton,HideButton等)所有操作同時調用..爲什麼這個事情? – 2012-01-09 06:55:07

0

我最近做了一個應用程序和我有同樣的情況,但我發現了另一種方式來解決這個問題,所以我決定分享我的人誰可能是在同樣的情況的解決方案。

我會盡力解釋我做了什麼這個問題的背景:

  • 我添加了一個標籤,我用的是button需要調用一個函數有關它buttonaMethodShow:例如)。

  • button始終調用相同的功能(例如,callSpecificFunc:)。什麼callSpecificFunc:所做的就是調用兩個函數aMethodShow:aMethodHide當前button標籤根據。

  • button需要調用不同功能的特定部分中,我只更改button的標籤。

事情是這樣的:

NSInteger tagOne = 1000; //tag associated with 'aMethodShow' func 
NSInteger tagTwo = 1001; //tag associated with 'aMethodHide' func 

button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button addTarget:self action:@selector(callSpecificFunc:) forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[view addSubview:button]; 

... 
// in some part of code, if we want to call 'aMethodShow' function, 
// we set the button's tag like this 
button.tag = tagOne 

... 

//Now, if we want to call 'aMethodHide', just change the button's tag 
button.tag = tagTwo 

... 

-(void) callSpecificFunc:(UIButton*)sender 
{ 
    NSInteger tagOne = 1000; 
    NSInteger tagTwo = 1001; 

    if([sender tag] == tagOne){ 
     //do whatever 'aMethodShow' does 
    }else { 
     //do whatever 'aMethodHide' does 
    } 
} 

當然,它可以應用於超過2個功能:)

8

我認爲它會幫助你

[yourButton removeTarget:nil 
       action:NULL 
    forControlEvents:UIControlEventAllEvents]; 

[yourButton addTarget:self 
       action:@selector(yourAction:) 
    forControlEvents:UIControlEventTouchUpInside]; 
相關問題