2.10. Displaying an Image on a Navigation Bar

Problem

You want to display an image instead of text as the title of the current view controller on the navigation controller.

Solution

Use the titleView property of the view controller’s navigation item:

- (void)viewDidLoad{
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor whiteColor];

  /* Create an Image View to replace the Title View */
  UIImageView *imageView =
  [[UIImageView alloc]
   initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 40.0f)];

  imageView.contentMode = UIViewContentModeScaleAspectFit;

  /* Load an image. Be careful, this image will be cached */
  UIImage *image = [UIImage imageNamed:@"FullSizeLogo.png"];

  /* Set the image of the Image View */
  [imageView setImage:image];

  /* Set the Title View */
  self.navigationItem.titleView = imageView;

}

Note

The preceding code must be executed in a view controller that is placed inside a navigation controller.

Discussion

The navigation item of every view controller can display two different types of content in the title area of the view controller to which it is assigned:

  • Simple text

  • A view

If you want to use text, you can use the title property of the navigation item. However, if you want more control over the title or if you simply want to display an image or any other view up on the navigation bar, you can use the titleView property of the navigation item of a view controller. You can assign any object that is a subclass of the UIView class. In our example, we created an image view and assigned ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.