how can i edit a table view section header ios swift

12,773

You can customise your section header by create customised UITableViewCell in storyboard.

You design 3 section as same as like snapshot in storyboard.

Here is the example of two section with two different UITableView cells I used

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {    
 //Say 2 section with two different look
 if section == 0{
    let header = tableView.dequeueReusableCellWithIdentifier("HeaderTableViewCell1")! as! HeaderTableViewCell1
    header._lblGroupName.text = ""
    header._btnExpand.addTarget(self, action: "hideSection:", forControlEvents: .TouchUpInside)

    header._lblTotalCount.text = ""
    return header.contentView
 }
 else{
   let header = tableView.dequeueReusableCellWithIdentifier("HeaderTableViewCell2")! as! HeaderTableViewCell2
    header._lblGroupName.text = ""
    header._btnExpand.addTarget(self, action: "hideSection:", forControlEvents: .TouchUpInside)

    header._lblTotalCount.text = ""
    return header.contentView
 }
}

Create two custom UITableViewCell classes. Set the outlet

class HeaderTableViewCell1: UITableViewCell {

@IBOutlet weak var _lblTotalCount: UILabel!
@IBOutlet weak var _btnExpand: UIButton!
@IBOutlet weak var _lblGroupName: UILabel!

}

class HeaderTableViewCell2: UITableViewCell {

@IBOutlet weak var _lblTotalCount: UILabel!
@IBOutlet weak var _btnExpand: UIButton!
@IBOutlet weak var _lblGroupName: UILabel!

}
Share:
12,773
sauly
Author by

sauly

Updated on November 30, 2022

Comments

  • sauly
    sauly over 1 year

    Im using a table view controller with headers for each of my three sections. I want to be able to change the look of the headers what would be the best way to do that.

    something similar to how snapchat stories page headers look

    • Lumialxk
      Lumialxk almost 8 years
      Post more details, code or screenshot.
  • sauly
    sauly almost 8 years
    thank you for the response im having a tough time really understanding this - anyway you could write in swift
  • Jason
    Jason almost 8 years
    Note: You should subclass UITableViewHeaderFooterView and return that. I wouldn't bother using a frame either. You should state the height as a constant under tableView.sectionHeaderHeight or implement tableView(_:heightForHeaderInSection:)
  • Connor Neville
    Connor Neville almost 7 years
    I'm not sure what the implications are of using cells for this, but I think you should be subclassing UITableViewHeaderFooterView. And UITableView has an accompanying dequeueReusableHeaderFooterView(withIdentifier:) function.