newme
newme

Reputation: 577

Can't change image of UIImageView

.h

IBOutlet UIImageView *photoImageView;
UIImage *photo;

.m (in viewWillAppear)

photoImageView.image = photo;

After view appeared, I can't change photoImageView by using:

photoImageView.image = [UIImage imageNamed:@"XXX.png"];

but changing the value of photo works.

photo = [UIImage imageNamed:@"XXX.png"];

How does it work?

Upvotes: 4

Views: 3613

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

Try this code.

//YourController.h

@interface YourController : UIViewController
{
    UIImageView* _photoImageView;
}

@property (retain, nonatomic) IBOutlet UIImageView *photoImageView;

- (IBAction)changeImageAction:(id)sender;

@end

//YourController.m

@synthesize photoImageView = _photoImageView;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.photoImageView.image = [UIImage imageNamed:@"img.png"];
}

- (IBAction)changeImageAction:(id)sender {

    self.photoImageView.image = [UIImage imageNamed:@"img_2.png"];
}

Some notes.

First of all, you have to link your photoImageView IBOutlet correctly in XCode. For test purposes I created a test button (UIButton) that is linked to an IBAction. The UIImageView and the test button (I created both with IB) are childs of YourController view.

Remember to import your images into your project and to release memory in dealloc and in viewDidUnload.

- (dealloc)
{
   [_photoImageView release];
   _photoImageView = nil;

   [super dealloc]
}

- (void)viewDidUnload
{
   [super viewDidUnload];

   self.photoImageView = nil;
}

Hope it helps.

Edit

The code is not ARC oriented but with few modifications it is possible to run it also with ARC.

Upvotes: 5

Related Questions