Friday, June 7, 2013

UITableView registerNib forHeaderFooterViewReuseIdentifier example in Objective C (iOS).

UITableView registerNib forHeaderFooterViewReuseIdentifier

Registers a nib object containing a header or footer with the table view under a specified identifier.

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

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

Discussion of [UITableView registerNib forHeaderFooterViewReuseIdentifier]
Prior to dequeueing any header or footer views, call this method or the registerClass:forHeaderFooterViewReuseIdentifier: method to tell the table view how to create new instances of your views. If a view of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new one 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 forHeaderFooterViewReuseIdentifier example.
You don't need to set the identifier in the xib -- you just need to use the same identifier when you register, and when you dequeue the header view. In the viewDidLoad method, I registered the view like this:

[self.tableView registerNib:[UINib nibWithNibName:@"Header1" bundle:nil] forHeaderFooterViewReuseIdentifier:@"header1"];
Then, in the delegate methods:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header1"];
    return headerView;

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 100;

End of UITableView registerNib forHeaderFooterViewReuseIdentifier example article.