4.1. Instantiating a Table View

Problem

You want to place a table view on your UI.

Solution

Instantiate an object of type UITableView and add it as a subview of any of your views.

Discussion

There are two ways of instantiating a table view:

  1. Through code

  2. Using Interface Builder

If you are using Interface Builder, creating a table view is as simple as dragging and dropping a table view from the object library into your .xib file. If you are more comfortable creating your components using code, then that is no problem either. All you have to do is to instantiate an object of type UITableView. Let’s start by defining our table view in our view controller’s header file:

#import <UIKit/UIKit.h>

@interface Instantiating_a_Table_ViewViewController : UIViewController

@property (nonatomic, strong) UITableView *myTableView;

@end

And creating the view controller is as easy as just allocating and initializing an instance of UITableView:

- (void)viewDidLoad{
  [super viewDidLoad];

  self.view.backgroundColor = [UIColor whiteColor];

  self.myTableView =
    [[UITableView alloc] initWithFrame:self.view.bounds
                                 style:UITableViewStylePlain];

  [self.view addSubview:self.myTableView];

}

The style parameter of the initWithFrame:style: initializer of the view controller allows us to specify what type of table view we need. There are two styles that we can choose from:

UITableViewStylePlain

Creates a plain table view with no background images.

UITableViewStyleGrouped

Creates a table view with a background image and rounded group borders, similar to the Settings app.

If you run your app right now on the iPhone Simulator, you will see the table view sitting there with no table view cells populated inside it (Figure 4-1).

A plain table view with no content

Figure 4-1. A plain table view with no content

Get iOS 6 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.