Monday, October 17, 2016

Custom TableView Section Headers

There are two ways you can add custom tableview section headers:
  • Build a view in code
  • Dequeue a prototype cell from the storyboard

In both cases 2 delegate methods must be implemented:
  1. viewForHeaderInSection
  2. heightForHeaderInSection

Building a View in Code

 
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = UIColor.orange
    
    let image = UIImageView(image: sectionImages[section])
    image.frame = CGRect(x: 5, y: 5, width: 35, height: 35)
    view.addSubview(image)
    
    let label = UILabel()
    label.text = sectionTitles[section]
    label.frame = CGRect(x: 45, y: 5, width: 100, height: 35)
    view.addSubview(label)

    return view
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 60
}
 

Dequeuing a Prototype Cell

 
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderCell

    cell.headerImage.image = sectionImages[section]
    cell.headerLabel.text = sectionTitles[section]

    return cell
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    switch section {
    case 0,2:
        return 45
    default:
        return 60
    }
}
 


(Xcode 8, Swift 3.0)

1 comment:

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...