2
votes

I currently have some custom section header views used in a UITableView. The views appear when the UITableView is loaded but disappears when scrolling. I saw this post but it seems outdated: tableView section headers disappear SWIFT Here is my code for the header view:

  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

      let view = UIView()

      switch section {
      case 0: break

      default:

        view.backgroundColor = UIColor.clear
        let image = UIImageView(image:"Line")
        image.frame = CGRect(x: 8, y: 35, width: 340, height: 1)
        view.addSubview(image)

        let label = UILabel()
        let sectionText = self.sectionTitles[section]
        label.text = sectionText
        label.textColor = UIColor.white
        label.font = UIFont(name:"Helvetica Neue" , size: 17)
        label.frame = CGRect(x: 10, y: 8, width: 200, height: 20)
        view.addSubview(label)
        }

      return view
  }


  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    let headerHeight: CGFloat

    switch section {
    case 0:
      // hide the first section header
      headerHeight = CGFloat.leastNonzeroMagnitude
    default:
      headerHeight = 40
    }

    return headerHeight
  }
1
Probably not relevant but why don't you return 0 for the height of the header in section 0? Why return the really tiny, almost 0 value instead of just 0?rmaddy
I tried that, it doesn't really make a differenceSwiftyJD
I would also suggest creating your header view with a more useful, non-zero initial frame.rmaddy

1 Answers

3
votes

The headers only remain fixed when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.

So if you want to fix headers that will stick on the top than you need to set UITableViewStyle to UITableViewStylePlain

if you want to scroll up with the cells than you need to set UITableViewStyle to UITableViewStyleGrouped