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

Leave a Reply

Your email address will not be published. Required fields are marked *