user3451350 user3451350 - 5 months ago 36
iOS Question

UIImageView set image programmatically bug

I have a UIImageView in a storyboard, connected to the header of the subclassed UIViewController like this:

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


In the
.m
of the UIViewController subclass, I try to set the image of the
displayPhoto
.

@synthesize displayPhoto;

-(void)awakeFromNib {
UIImage *image = [UIImage imageNamed:@"dp.jpg"];

[displayPhoto setImage:image];

displayPhoto.layer.cornerRadius = displayPhoto.image.size.width/2;

[self.view addSubview:displayPhoto];
}


but it does absolutely nothing. If I add one more line, adding another view of the image like so:
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];
, making my methodf

@synthesize displayPhoto;

-(void)awakeFromNib {
UIImage *image = [UIImage imageNamed:@"dp.jpg"];

[self.view addSubview:[[UIImageView alloc] initWithImage:image]];

[displayPhoto setImage:image];

displayPhoto.layer.cornerRadius = displayPhoto.image.size.width/2;

[self.view addSubview:displayPhoto];
}


It suddenly starts working and adds to instances of the image to the view. One in the top left corner (from the line I added) and a second in the storyboard image location.

What's changing? How is adding that one line making my code work and is there any work around so I can make the image just show up as normal?

Answer

If you added the UIImage in your storyboard and connected the outlet correctly, there is no need to create a new image programmatically. Try this.

- (void) viewDidLoad {
     [super viewDidLoad];
     self.displayPhoto.image = [UIImage imageNamed:@"dp.jpg"];
}
Comments