I want to have a pointer to an UIImage view so that I don’t have to repeat a lot of my code. I need to choose the image based on which button it is but then at the end I apply the same code to whatever digit. oneDigit, twoDigit, and threeDigit are all @property(nonatomic, retain) in the header file. I want imageView to be able to point to one of these UIImageViews. Right now the UIImageViews are not being removed with removeFromSuperview because imageView is not pointing to the objects but creating its own object..
Currently when a button is pressed a Image is added. I want the previous image removed and the new image drawn according to what button was pressed. The code works how I want if I replace imageView with oneDigit, but that would require me to add more code for each variable.
See simplified example below:
- (void)viewDidLoad
{ ...
UIImageView *oneDigit;
UIImageView *twoDigit;
UIImageView *threeDigit;
}
-(IBAction)pressButton:(id)sender {
UIImage *image;
UIImageView *imageView;
UIButton *btn = (UIButton*)sender;
int value = [btn.titleLabel.text intValue];
switch (value) {
case 10:
case 15:
case 20:
[twoDigit removeFromSuperview]; //Remove old image from screen
imageView = twoDigit; //Update imageView pointer for current case
image = [UIImage imageNamed:@"twoDigit.png"];
break;
case 1:
case 2:
case 3:
case 4:
case 5:
[oneDigit removeFromSuperview];
imageView = oneDigit;
image = [UIImage imageNamed:@"oneDigit.png"];
break;
case 100:
case 200:
case 300:
[threeDigit removeFromSuperview];
imageView = threeDigit;
image = [UIImage imageNamed:@"threeDigit.png"];
break;
default:
break;
}
CGPoint point = btn.frame.origin;
CGFloat xposition = point.x - ((image.size.width - btn.frame.size.width) /2);
CGFloat yposition = point.y - ((image.size.height - btn.frame.size.height) /2);
imageView = [ [ UIImageView alloc ] initWithFrame:CGRectMake(xposition, yposition, image.size.width, image.size.height) ];
imageView.image = image;
imageView.contentMode = UIViewContentModeCenter;
[self.view addSubview:imageView];
}
Assuming that oneDigit, twoDigit and threeDigit are UIImageViews, you can just do something similar to
Since both are pointers, setting imageView to oneDigit will simply point imageView to the location of oneDigit. When you set it to the new image, don’t autorelease it first, because if it’s set to threeDigit for example, it will autorelease threeDigit too.
Also, you don’t need to set the image property of imageView manually after setting imageView to the new image, because it’s essentially referencing the exact same UIImageView with the same image; it’s just under a different name.