Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable TableView header views

For performance sake it is usual to reuse UITableView' cells. Is there a way to do the same thing with TableView header' views? I am talking about the ones that are returned with delegate's method:

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

I tried to do the following which doesn't seem to be working as expected:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {     static NSString *CellIdentifier = @"Header";      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];     if (cell == nil) {         cell = [self getHeaderContentView: CellIdentifier];     }     return cell; } 

Is there a way to reuse header' views?

like image 924
Ilya Suzdalnitski Avatar asked Jun 06 '09 17:06

Ilya Suzdalnitski


People also ask

How can I make the Footerview always stay at the bottom in Uitableviewcontroller?

If you need to make the footer view fixed at the bottom then you can not use a TableViewController . You will have to use UIViewController , put your tableView as a subview. Put the footer also as another subview and its done.


1 Answers

The reason Apple built in the ability to reuse tableview cells is because while the tableview may have many rows, only a handful are displayed on screen. Instead of allocating memory for each cell, applications can reuse already existing cells and reconfigure them as necessary.

First off, header views are just UIViews, and while UITableViewCell is a subclass of UIView, they are not intended to be placed as the view of a section header.

Further, since you generally will have far fewer section headers than total rows, there's little reason to build a reusability mechanism and in fact Apple has not implemented one for generic UIViews.

Note that if you are just setting a label to the header, you can use -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section instead.

For something more custom, such as a label with red text (or a button, image, etc), you can do something like this:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {   UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 44)] autorelease];   UILabel *label = [[[UILabel alloc] initWithFrame:headerView.frame] autorelease];   label.textColor = [UIColor redColor];   label.text = [NSString stringWithFormat:@"Section %i", section];    [headerView addSubview:label];   return headerView; } 
like image 181
Martin Gordon Avatar answered Sep 29 '22 01:09

Martin Gordon