简体   繁体   中英

UITableView section header views disappear when scrolling

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
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM