Matt Langtree

UITableView Section Header Draw Issue in iOS5

If you are using custom section header views in your UITableView you would have implemented UITableViewDelegate’s following two delegate methods:

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

If you are using the same code for tables with and without section headers there’s a good chance that you have some logic like the code below. The important point to note with the release of iOS5 is that it is no longer suitable in iOS5 to only return nil on the - (UIView ) tableView:(UITableView )tableView viewForHeaderInSection:(NSInteger)section if you don’t want the section header to show. You now need to explicitly set a height of 0 for the section header.

If you don’t follow this rule, you may end up with an empty section header being drawn, like so:

New UITableView code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
  // This is the new important bit for iOS5.
  if ([self currentViewNeedsTableHeaders] ) {
      return 0;
  }
  
  return 45;
}
// Will produce a green view with a black bottom separator line.
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  if ([self currentViewNeedsTableHeaders] ) {
      return nil;
  }

  // How wide is the screen?
  float w = [[UIScreen mainScreen] bounds].size.width;
  headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0, w, 44.0)];
  headerLabel.text = [self tableView:tableView titleForHeaderInSection:section];
  headerLabel.backgroundColor = [UIColor colorWithRed:0.431 green:0.820 blue:0.137 alpha:1.0];
  headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, 45)];
  headerView.backgroundColor = [UIColor blackColor];
  headerLabel.font = [UIFont boldSystemFontOfSize:15];
  
  // Add Label to the headerView's view hierarchy
  [headerView addSubview:headerLabel];
  return headerView;
}
- (BOOL)currentViewNeedsTableHeaders
{
  return ([self.someProperty isEqualToString:@"parrot"]) ? FALSE : TRUE;
}