Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement Custom Table View Section Headers and Footers with Storyboard

Without using a storyboard we could simply drag a UIView onto the canvas, lay it out and then set it in the tableView:viewForHeaderInSection or tableView:viewForFooterInSection delegate methods.

How do we accomplish this with a StoryBoard where we cannot drag a UIView onto the canvas

like image 763
Seamus Avatar asked Feb 09 '12 21:02

Seamus


2 Answers

Just use a prototype cell as your section header and / or footer.

  • add an extra cell and put your desired elements in it.
  • set the identifier to something specific (in my case SectionHeader)
  • implement the tableView:viewForHeaderInSection: method or the tableView:viewForFooterInSection: method
  • use [tableView dequeueReusableCellWithIdentifier:] to get the header
  • implement the tableView:heightForHeaderInSection: method.

(see screenhot)

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {     static NSString *CellIdentifier = @"SectionHeader";      UITableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];     if (headerView == nil){         [NSException raise:@"headerView == nil.." format:@"No cells with matching CellIdentifier loaded from your storyboard"];     }     return headerView; }   

Edit: How to change the header title (commented question):

  1. Add a label to the header cell
  2. set the tag of the label to a specific number (e.g. 123)
  3. In your tableView:viewForHeaderInSection: method get the label by calling:
    UILabel *label = (UILabel *)[headerView viewWithTag:123];  
  1. Now you can use the label to set a new title:
    [label setText:@"New Title"]; 
like image 99
Tieme Avatar answered Dec 02 '22 02:12

Tieme


I know this question was for iOS 5, but for the benefit of future readers, note that effective iOS 6 we can now use dequeueReusableHeaderFooterViewWithIdentifier instead of dequeueReusableCellWithIdentifier.

So in viewDidLoad, call either registerNib:forHeaderFooterViewReuseIdentifier: or registerClass:forHeaderFooterViewReuseIdentifier:. Then in viewForHeaderInSection, call tableView:dequeueReusableHeaderFooterViewWithIdentifier:. You do not use a cell prototype with this API (it's either a NIB-based view or a programmatically created view), but this is the new API for dequeued headers and footers.

like image 40
Rob Avatar answered Dec 02 '22 02:12

Rob