Asp Upload Asp Upload - 3 months ago 21
iOS Question

How to load image inside the UIImageView created using Interface Builder?

I created an UIImageView using xib. When I used the following codes, the image appears on the top left hand corner on the simulator. Although I have set the bottom constraint of the UIImageView to be 45 above the black button using the Interface Builder, it didn't work.

I would like the image to show at the location where I placed the UIImageView using xib. Please help! Thanks!

UIImage *image = [UIImage imageNamed:@"picture.jpg"];
self.imageHolder = [[UIImageView alloc] initWithImage:image];
self.imageHolder.image = image;
[self.view addSubview:self.imageHolder];


UIImageView

Answer

In the way you described, you're initialising two UIImageViews: one in your XIB and one in code. You don't need these lines:

UIImage *image = [UIImage imageNamed:@"picture.jpg"];
self.imageHolder = [[UIImageView alloc] initWithImage:image];
self.imageHolder.image = image;
[self.view addSubview:self.imageHolder];

Just create an IBOutlet property of your UIImageView to the corresponding view controller like this:

@property (nonatomic, weak) IBOutlet UIImageView *imageView;

The property doesn't need any initialisation. Just put this in your viewDidLoad method:

self.imageView.image = [UIImage imageNamed:@"picture.jpg"];

If the image won't be set dynamically, set it in your XIB at the Attributes Inspector.