Reputation: 2437
I use 20 UIButtons in my application .i set the background image of all these UIButtons on click event.all these UIButton are save in NSMutableArray.here is code.
saveBtn = [[NSMutableArray alloc] init];
for (int i=0; i<20; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(spacex, spacey, 30.0, 30.0);
idx = arc4random()%[arr count];
NSString* titre1 = [arr objectAtIndex:idx];
[btn setTitle:titre1 forState:UIControlStateNormal];
spacex = spacex + 30;
[saveBtn addObject:btn];
[self.view addSubview:btn];
}
i don it successful here is my code.
UIButton *currentButton = (UIButton *)sender;
UIImage * imgNormal = [UIImage imageNamed:@"subtabButton.png"];
[currentButton setBackgroundImage:imgNormal forState:UIControlStateNormal];
[currentButton setTitle:currentButton.titleLabel.text forState:UIControlStateNormal];
But between these 20 UIButtons there are 3 UIButtons ,i want that when player click one of these three UIButtons,all the previous set background images are remove from UIButtons.can any one guide me how we can do it..thanx in advance.
Upvotes: 1
Views: 1271
Reputation: 5314
From my understanding you have 20 buttons, where 3 of those buttons remove the Image for the other 17.
If the 3 that control this function are in the array, i suggest you remove them from it because looping over your array of buttons will also remove the images from the 3 main
buttons.
Alternatively you should use a tag
to differentiate the 3 main buttons. Your button(s) action should look something like this.
-(void)buttonPressed:(id)sender {
UIButton *button = (UIButton*)sender;
if(button.tag == 1001 || button.tag == 1002 || button.tag == 1003) {
for (UIButton *btn in buttonArray) {
[btn setBackgroundImage:nil forState:UIControlStateNormal];
}
}
}
I may be misunderstanding your need, but this is what I came up with. Hope it helps !
Upvotes: 1
Reputation: 7348
for (UIButton *btn in yourArrayOfButtons)
{
[btn setBackgroundImage:[UIImage imageNamed:@"nameofmyimage"] forState:UIControlStateNormal];
}
or if you want to remove the image:
for (UIButton *btn in yourArrayOfButtons)
{
[btn setBackgroundImage:nil forState:UIControlStateNormal];
}
Upvotes: 5
Reputation: 12904
Probably the best way to do this is create each button dynamically. Store each buttons information into an NSMutableArray then do a for loop to remove the images.
[currentButton setBackgroundImage:nil forState:UIControlStateNormal];
would remove the button's image. Its kind of hard to help you without seeing how your buttons are stored in an array.
Upvotes: 1
Reputation: 4977
Put all the buttons in an NSArray or NSMutableArray when they're created. Then use a for-in loop, or a simple for loop to change the background for all of them.
Upvotes: 2