UIButton UIControl针对单个按钮的目标动作2动作

时间:2014-12-02 10:31:11

标签: ios uibutton uicontrol

我有一个具有选定和未选中状态的按钮。

按钮的目标操作代码是:

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];
}

3 个答案:

答案 0 :(得分: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
   }

答案 1 :(得分:0)

我相信你想要切换按钮之类的东西。如果我是正确使用yourbutton.currentTitle来遵循功能。即如果[youtbutton.currentTitle isEqualToString: @"save]",则应执行保存并将其设置为删除,反之亦然

答案 2 :(得分: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];
}
}