Friday, June 7, 2013

UITableView registerNib example in Objective C (iOS).


UITableView registerNib

Registers a nib object containing a cell with the table view under a specified identifier.

- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier

Parameters of [UITableView registerNib]
nib
A nib object that specifies the nib file to use to create the cell. This parameter cannot be nil.
identifier
The reuse identifier for the cell. This parameter must not be nil and must not be an empty string.

Discussion of [UITableView registerNib]
Prior to dequeueing any cells, call this method or the registerClass:forCellReuseIdentifier: method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically.

If you previously registered a class or nib file with the same reuse identifier, the nib you specify in the nib parameter replaces the old entry. You may specify nil for nib if you want to unregister the nib from the specified reuse identifier.

UITableView registerNib example.
Create your xib file with a UITableViewCell as the top-level object. This is called Cell.xib
Create a UINib object based on this file
Register the UINib with the table view (typically in viewDidLoad of your table view controller subclass).
Steps 2 and 3 can be combined, so you would use the following line in viewDidLoad:

[self.tableView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellReuseIdentifier:@"Cell"];
Then, in cellForRowAtIndexPath, if you want one of the cells from the nib, you dequeue it:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
This either creates a new instance from the nib, or dequeues an existing cell.


Example of [UITableView registerNib].
- (void)viewDidLoad
{
 [super viewDidLoad];
 UINib *nib = [UINib nibWithNibName:@"ItemCell" bundle:nil];
 [[self tableView] registerNib:nib forCellReuseIdentifier:@"ItemCell"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

// Create an instance of PointsItemCell
PointsItemCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"ItemCell"];


return cell;
}

UITableView registerNib example.
If you're using iOS 5 you can use

[self.tableView registerNib:[UINib nibWithNibName:@"nibname"
                                           bundle:nil]
     forCellReuseIdentifier:@"cellIdentifier"];
Then whenever you call:

cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
the tableview will either load the nib and give you a cell, or dequeue a cell for you!

The nib need only be a nib with a single tableviewcell defined inside of it!


End of UITableView registerNib example article.