How to Add a Background Image and Title to Your iOS App

By Jesse Feiler

The type of Table view many iOS app programmers use has static cells that you set up in Interface Builder. However, in this view, everything isn’t static — including two things based on the destination. Those two things are the background image and the title. You have to set those programmatically.

Start by hiding the Utility area and then show the Project navigator (if you have hidden it) by making the appropriate selections in the toolbar. Then select MasterViewConroller.m in the Project navigator.

The View Controller method you’d use to customize a view at launch time is viewDidLoad, which is the method used here as well.

First, import the headers you need by adding the bolded code to MasterViewController.m.

#import "MasterViewController.h"#import "DetailViewController.h"#import "AppDelegate.h"#import "Trip.h"

Now add the bolded code to the viewDidLoad method in MasterViewController.m and delete the commented out code in bold, underline, and italic.

- (void)viewDidLoad
{
 [super viewDidLoad];
//self.title = @"Road Trip";
 AppDelegate* appDelegate = [[UIApplication
        sharedApplication] delegate];
 self.title = appDelegate.trip.destinationName;
 UIImageView* imageView = [[UIImageView alloc]
  initWithImage:[appDelegate.trip destinationImage]];
 self.tableView.backgroundView = imageView;
_

You want to add two features to the MasterViewConroller’s view. The first makes the title in the Navigation bar the name of the destination, and the second adds a background image to the view.

To get the information the Master View controller needs from the (Trip) model, it needs to send a message to the Trip object.

You find AppDelegate by sending the class message to the UIApplication class and then sending the delegate message to the UIApplication object.

You use the following two methods to place your background image and display the destination name:

  • destinationImage is a Trip method that returns a UIImage pointer.

  • destinationName is a Trip method that returns an NSString pointer that contains the destination name.

There’s one final step: Beginning with iOS 7, the background color of all table cells is white (although the Interface Builder interface may lead you to think otherwise). You need to set the background color of the table cells to clear so that your background image will show through. Do this by adding this code to MasterViewConroller.m.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
 cell.backgroundColor = [UIColor clearColor];
}

Run the app now and select Travel. Be prepared to be impressed with your work.

image0.jpg