O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.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 then we will go ahead and synthesize the table view in the implementation file of our view controller:

#import "Instantiating_a_Table_ViewViewController.h"

@implementation Instantiating_a_Table_ViewViewController

@synthesize myTableView;

...

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required