Search code examples
iosios7

Enabling and disabling multiple buttons in view issue


I have a view with 12 buttons. I want to be able to perform the action's button just once when i tap it and then set that specific button disabled. When i tap on another button i want the same thing to happen + set the other buttons enabled. Is there a solution?


Solution

  • You can give to each button a tag, and when you tap on a button using method viewWithTag you can enable and disable each button:

    When you create UIButton, you can add:

    UIButton *button0 = ...
    button0.tag = 0;
    
    UIButton *button1 = ...
    button1.tag = 1;
    
    //and so on
    

    In every action of the buttons, you must pass the id object like this:

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