Question

I have a multiple array of buttons called button. Each one is tagged. How do I change the image on the button based on its tag and tag only. As of right now, it only changes the very last button.

    -(void)buttonTapped:(id)sender{

     NSLog (@"%i",[sender tag])];

      [button setImage:[UIImage imageNamed:@"button_change.png"] forState:UIControlStateNormal];
        }

No correct solution

OTHER TIPS

Either:

for (UIButton *btn in button) {
    if(btn.tag == 1)
    {
        // do something
        break; // don't need to run the rest of the loop
    }
}

if you want to use the array (it shouldn't be called 'button', use something with a plural for an array)

or an easier way:

UIButton *btn = (UIButton *)[self.view viewWithTag:1];

However a much simpler way would be to use the param in the callback (unless thats not the button you want). Like so:

-(void)buttonTapped:(id)sender
{
     UIButton *tappedBtn = (UIButton *)sender;
     [tappedBtn setImage:[UIImage imageNamed:@"button_change.png"] forState:UIControlStateNormal];
}

If you just want to change the button that was tapped the following should work.

   -(void)buttonTapped:(id)sender
   {
     NSLog (@"%i",[sender tag])];
     UIButton *tappedButton = (UIButton *)sender;
     [tappedButton setImage:[UIImage imageNamed:@"button_change.png"] forState:UIControlStateNormal];
   }

If you want to change other buttons then you can retrieve the buttons using

[self.view viewWithTag:1000]; //1000 is the tag you assigned

You don't really need to use tags in the this case. When an IBAction is invoked, the sender parameter is a pointer to the control that triggered the IBAction. (Your button.)

Thus, you already have a pointer to the button.

So, as others have pointed out, your code could read like this:

-(void)buttonTapped:(UIButton *)sender
{
  [sender setImage:[UIImage imageNamed:@"button_change.png"] forState:UIControlStateNormal];
}

Note that I changed the type of sender to UIButton so that you don't have to cast it. As long as the action is only ever connected to a button, this is safe to do and makes the code cleaner.

As the other poster pointed out, having an array of buttons called "button" is bad. I renamed it to "buttons" in the code below:

If you wanted to do it using tags and an array of buttons, you could use code like this:

-(void)buttonTapped:(UIButton *)sender
{
  NSUInteger tag = [sender tag];
  UIButton *aButton = buttons[tag];
  [aButton setImage:[UIImage imageNamed:@"button_change.png"] forState:UIControlStateNormal];
}

Create images with names button_change1.png, button_change2.png, etc.

And:

-(void) buttonTapped:(UIButton*)sender
{
    NSString* imageName = [NSString stringWithFormat: @"button_change%ld.png", (long)sender.tag];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top