1.22. 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 instantiate an object of type UIImageView and add it to your views. Now, I
have a picture of a MacBook Air, and I would like to display it in an
image view. Let’s start with our view controller’s implementation
file:
#import "ViewController.h"@interfaceViewController()@property(nonatomic,strong)UIImageView*myImageView;@end@implementationViewController
Go ahead and instantiate the image view and place the image in it:
-(void)viewDidLoad{[superviewDidLoad];UIImage*macBookAir=[UIImageimageNamed:@"MacBookAir"];self.myImageView=[[UIImageViewalloc]initWithImage:macBookAir];self.myImageView.center=self.view.center;[self.viewaddSubview:self.myImageView];}
Now if we run the app, we will see something similar to Figure 1-60.

Figure 1-60. An image view that is too big to fit on the screen
I should mention that the MacBook Air image that I’m loading into this image view is 980×519 pixels, and as you can see, it certainly doesn’t fit into the iPhone screen. So how do we solve this problem? First, we need to make sure that we ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access