Reputation: 171
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];
Upvotes: 1
Views: 2193
Reputation: 557
IOS will automatically look for your file "overflow.png" in the same bundle as your xib file. If your xib file is just in your application's target, then by default it looks inside the main bundle.
If you want to programatically load a new image into an image view and your image is inside the main bundle:
UIImage *image = [UIImage imageNamed:@"MyAwesomeImage"];
self.imageView = image;
If your image is inside another bundle:
NSBundle *imageBundle = ... // [NSBundle mainBundle] if your image is inside main bundle
NSString *imagePath = [imageBundle pathForResource:@"MyAwesomeImage" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
self.imageView.image = image;
Upvotes: 1
Reputation: 1057
First click on the "show the assistant editor button to both show interface builder & code
Then click+ctrl button and drag Image to code to create an IBOutlet.
@property (weak, nonatomic) IBOutlet UIImageView *sunImage;
Then in -(void)viewdidload
or where you would like to set image
UIImage *image = [UIImage imageNamed:@"picture.jpg"];
[self.sunImage setImage:image];
Upvotes: 0
Reputation: 252
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.
Upvotes: 0