How to programmatically set image to UIImageView or NSImageView in Xcode?

Here is how to programmatically set image to UIImageView in Xcode,

 
Step 01: In your Xcode project in storyboard drag UIImageView from object library (located at Xcode right utilities sidebar). Give it definite size & now note down it’s size on paper to create same size image in you choice of image editor.

 
Step 02: Connect UIImageView to respective header file with name e.g. imageView

 
Your code will look something like this:

 

@property (strong) IBOutlet NSImageView *imageView; // Code for OSX App

 

@property (strong, nonatomic) IBOutlet UIImageView *imageView; // Code for iOS App

 
Step 03: Now import image to current Xcode project with @1x, @2x, @3x (or may be @4x in future). You can Xcode’s inbuilt ‘Image Assets’ catalogue also.

 
Stpe 04: No in your selected function put below code. I assume that image you imported to your project it’s name is “coloured-image”

 

[_imageView setImage: [NSImage imageNamed:@"coloured-image"]]; // Code for OSX App

 

[_imageView.image = [UIImage imageNamed:@"coloured-image"]]; // Code for iOS App

 
Now build & run your project on your iOS Device, Mac or in your simulator. Your image should appear in the respective view.

 
Thanks & Regards
Mandar Apte

Published by Mandar Apte

Mandar is a Mumbai-based multi-disciplinary designer with UX/UI, Logo, Symbol, and Brand Identity design expertise. He currently runs his Mudrkashar Linguistic Apple iPhone, iPad, and Mac app business in the heart of Mumbai city.

Leave a comment

Leave a Reply