Alex Rivera | Logout

iPhone UITableView with a header area

Asked 2010-01-26T22:44:36.123
38

I have a view that was created with all of the default UITableView stuff, but now I need to add a header area above where the UITableView is (so the UITableView will scroll normally, but the top 100px of the screen or so will have static header content). I don't see where I can resize the UITableView in IB, and am not sure how to do this.

Does anyone know?

Edit
Report

2 Answers

57

You can use UITableViewDelegate methods to create a custom header view for a table and specify the height, namely tableView:viewForHeaderInSection: and tableView:heightForHeaderInSection:. You can add whatever you like to the view. Here's an example that adds a right aligned UILabel:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = [titleArray objectAtIndex:section];
    headerLabel.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel];

    return headerView;

}

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

    return  30.0;
}
answered 2011-04-20T12:09:01.317
0

Suppose to have your UITableViewController

@interface MXMTableViewController : UITableViewController <UITableViewDelegate,UIScrollViewDelegate> {
/// your table view interface here
}

and a xib with you simple UITableView defined yet in it, you can do as Mihir says overriding the loadView method like this:

- (void)loadView {

    [super loadView];

    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    self.view = mainView;

    [mainView release];

    // Add Header View
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 36)];
    headerView.backgroundColor = [UIColor redColor];
    [self.view addSubview:headerView];

    // now, move your table view down. Check you nib to choose 
    // the right Y-axis offset
    CGRect f = tableView.frame;
    f.origin.y += headerView.frame.size.height/2;
    tableView.frame = f;

    // Add the table view to the container view
    [self.view addSubview:self.tableView];

    // Add footer
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tableView.frame.size.height, 320, 125)];
    footerView.backgroundColor = [UIColor redColor];
    [self.view addSubview:footerView];
    [footerView release];

    [headerView release];

}

...and that's it. You have a UITableView with fixed header and footer.

PS. You may now use your xib custom views as the header and footer's views.

answered 2011-06-27T16:14:03.290

Your Answer