I’m using this to define a grid of buttons. I want to programmatically change the attribute of a specific button, like:
if(button.tag == 6)
{
[button setBackgroundImage:imageRed forState:UIControlStateNormal];
[button setImage:imageRed forState:UIControlStateNormal];
}
Button creation below.
for (int y=0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//button.frame = CGRectMake(40 + 80 * x, 40 + 80 * y, 80, 80);
button.frame=CGRectMake(5+5*x,5+5*y,5,5);
unsigned buttonNumber = y * 3 + x + 1;
button.tag = buttonNumber;
//[button setTitle:[NSString stringWithFormat:@"%u", buttonNumber] forState:UIControlStateNormal];
[button setBackgroundImage:imageWhite forState:UIControlStateNormal];
[button setImage:imageWhite forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: button];
}
}
I’m not entirely sure what your question is, but it seems like ‘how do I find a view with a specific tag?’. The answer is the UIView method
This will look through the current view and all it’s subviews for the specified tag and return the first view it finds that matches it. So to get, for example, the button with tag 6, just do:
Of course, when dealing with a target method, like your
buttonPressed:method, the view that triggered the event is passed as a parameter, so you can also use that if that’s the only time you need it. Other than that everything in your code looks fine.