Cover by Vandad Nahavandipoor

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

2.17. Displaying Images with UIImageView

Problem

You would like to display images to your users on your app’s UI.

Solution

Use the UIImageView class.

Discussion

The UIImageView is one of the least complicated classes in the iOS SDK. As you know, an image view is responsible for displaying images. There are no tips or tricks involved. All you have to do is to instantiate an object of type UIImageView and add it to your views. Now, I have a picture of Apple MacBook Air and I would like to display it in an image view. Let’s start with our view controller’s header file:

#import <UIKit/UIKit.h>

@interface Displaying_Images_with_UIImageViewViewController
           : UIViewController

@property (nonatomic, strong) UIImageView *myImageView;

@end

Then synthesize the property in your implementation file:

#import "Displaying_Images_with_UIImageViewViewController.h"

@implementation Displaying_Images_with_UIImageViewViewController

@synthesize myImageView;

...

Go ahead and instantiate the image view and place the image in it:

- (void)viewDidLoad{
  [super viewDidLoad];

  self.view.backgroundColor = [UIColor whiteColor];

  UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir.png"];
  self.myImageView = [[UIImageView alloc] initWithImage:macBookAir];
  self.myImageView.center = self.view.center;
  [self.view addSubview:self.myImageView];

}

Now if we run the app, we will see something similar to Figure 2-55.

An image view that is too big to fit into the screen

Figure 2-55. An image ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required