在视图问题中启用和禁用多个按钮

时间:2014-11-19 16:12:01

标签: ios ios7

我有12个按钮的视图。我希望能够在点击它时只执行一次操作按钮,然后将该特定按钮设置为禁用。当我点击另一个按钮时我想要发生同样的事情+设置其他按钮启用。有解决方案吗?

2 个答案:

答案 0 :(得分:0)

您可以为每个按钮添加标签,当您使用方法viewWithTag点按按钮时,您可以启用和禁用每个按钮:

创建UIButton时,您可以添加:

UIButton *button0 = ...
button0.tag = 0;

UIButton *button1 = ...
button1.tag = 1;

//and so on

在按钮的每个操作中,您必须像这样传递id对象:

-(void)tapButtonOne:(id)sender {

   //with this sender you can retrive the tag of the button clicked
   UIButton *button = sender;
   int buttonTag = button.tag

   //now you can check every button and enable the other that haven't the same buttonTag
   //with the first tag = 0 plus 12 the last tag will be 11 so i<12
   for (int i = 0; i<12; i++) {
     //self.view if you have added the buttons on self.view, otherwise you must write your view
     UIButton *buttonTemp = (UIButton *)[self.view viewWithTag:i];
     if(buttonTemp.tag != buttonTag) {

       buttonTemp.enabled = YES;
     }
     else {
       buttonTemp.enabled = NO;
     }
   }
}

答案 1 :(得分:0)

创建IBOutletCollection,而不是创建插座 从界面构建器拖动到应用程序时,可以将“Outlet”选项更改为“Outlet Collection” 完成第一个按钮后,控制拖动所有按钮并将它们链接到同一个集合 将所有按钮连接到同一IBAction并确保它指定发件人(这是默认值)。 然后,在你的行动中:

for (UIButton* button in self.yourOutletCollection){
    if (button == sender){
        // this is the button that was tapped
    } else {
        // all the other buttons go here
    }
 }

享受!