2014-12-02 73 views
0

我有一個按鈕,它具有選定和未選中的狀態。UIButton UIControl單個按鈕的目標操作2操作

我對按鈕目標行動碼是這樣的:

NSArray *targets = [myButton actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]; 

    if ([targets count] == 0) { 
     [myButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside]; 

當按下按鈕時,它前進到選擇狀態中的方法。

如果選中該按鈕,則應調用其他操作。這樣做有沒有意想不到的結果,或者有沒有辦法用UIControlState添加動作呢?

if (myButton.selected == NO){ 
[myButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside]; 
} 
else{ 
[myButton addTarget:self action:@selector(delete:) forControlEvent:UIControlEventTouchUpInside]; 
} 
+0

它看起來OK,沒有什麼不好的實現 – 2014-12-02 10:33:06

回答

0
-(IBAction)myButton:(id)sender 
{ 
UIButton *btn = (UIButton*)sender; 
btn.selected = !btn.selected; 
if(btn.selected) 
{ 
    //Do whatever you want when button is selected 
    [self delete]; 
} 
else 
{ 
    //Do whatever you want when button isDeselected 
    [self save]; 
} 
} 
+0

什麼是btn.selected =!btn.selected嗎? – noobsmcgoobs 2014-12-03 04:16:51

+0

btn.selected =!btn.selected選擇按鈕的狀態和取消選擇! – 2014-12-03 04:42:22

0

您的方法可能會引起混淆。你可以像這樣使用。

[myButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    - (void)buttonPressed:(UIButton *)sender 
    { 
     if(sender.selected) 
     [self save]; 
     else 
     [self delete]; 
    } 
    -(void)save 
    { 
    // your code 
    } 
    -(void)delete 
    { 
    // your code 
    } 
0

我相信你想要的東西像切換按鈕。如果我正確使用yourbutton.currentTitle來跟蹤功能。即,如果[youtbutton.currentTitle isEqualToString: @"save]",那麼你應該進行保存和設置,刪除,反之亦然