Friday, June 7, 2013

UITableView tableHeaderView example in Objective C (iOS).


UITableView tableHeaderView

Returns an accessory view that is displayed above the table.

@property(nonatomic, retain) UIView *tableHeaderView

Discussion of [UITableView tableHeaderView]
The default value is nil. The table header view is different from a section header.

UITableView tableHeaderView example.
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (headerView == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"DetailContactHeader" owner:self options:nil];
        headerView.nameLabel.text = [NSString stringWithFormat:@"%@ %@",
                                                   [contact objectForKey:@"name"],
                                                   [contact objectForKey:@"familyname"]];
        if ([[contact allKeys] containsObject:@"pictureurl"]) {
            headerView.avatarView.image = [UIImage imageNamed:[contact objectForKey:@"pictureurl"]];
        }
    }
    [self.tableView setTableHeaderView: headerView];
}

Example of [UITableView tableHeaderView].
For example, in a UITableViewController:

-(void)viewDidLoad
{
     // ...
     UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:imageView];
     UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:labelView];
     self.tableView.tableHeaderView = headerView;
     [imageView release];
     [labelView release];
     [headerView release];
     // ...

UITableView tableHeaderView example.
-(UIView *) customHeaderView {
    if (!customHeaderView) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
    }

    return customHeaderView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set the CustomerHeaderView as the tables header view
    self.tableView.tableHeaderView = self.customHeaderView;
}

End of UITableView tableHeaderView example article.