I have about 10 UIImageView controls named pop1 to pop10.
I have 10 buttons each over a UIImageView. The buttons have a "tag" from 1 to 10 so I know which button is being pressed by:
UIButton * aButton =(UIButton *)sender;
aButton.tag - gives me the tag
I want to reference the UIImageView under the button to change its image when the button above it is pressed:
UIImage *image = [UIImage imageNamed: @"NewImage.png"];
[pop1 setImage:image];
But in the above code I do not want to hardcode the "pop1" or "pop2" etc. I want to build a string using the button tag
NSString *img = [NSString stringWithFormat:@"pop%d",aButton.tag];
gives me "pop1" or "pop2" etc, since I am using the aButton.tag.
So using this info how can I write code to reference the UIImage to change its image?
In his line, the "pop1" needs to be changed so it uses the built string - img:
[pop1 setImage:image];
I do NOT want to have to type in a switch statement for each tag as later on I intend to add a large number of such controls and that is not an option.
Is there a way or is there any other approach I can use?
Update
I tried the answer given by John in code like this
-(IBAction)pop:(id)sender{
UIButton * aButton =(UIButton *)sender;
NSLog(@"clicked button with TAG %d",aButton.tag);
if (aButton.tag > 0) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:aButton.tag];
UIImage *ix = [UIImage imageNamed:@"Newimage.png"];
[img setImage:ix];
// stop any more clicks
aButton.tag = 0;
}
}
Everything builds ok but on running, I get an error because "img" shows up in the debug window as a "UIButton" not a UIImage ( i think).
I am totally puzzled by this as in IB the control shows up as Class:UIImageView yet in code I am referencing it as UIImage? Are they interchangable?
How do I access the "tag" property of the "UIImageView - Displays a single image or animation described by an array of images(help)"
Bascically the buttons also have a tag so if button 2 is clicked it's tag is 2. So I want to change the image of UIImageView with tag = 2 and so on.
I am currently learning C/C and such a simple task in most other languages is so tedious in this.
I am at a loss. Help please.