UITableView滚动时,section header视图消失

3

我目前在UITableView中使用一些自定义的section header视图。这些视图出现在UITableView加载时,但在滚动时消失。我看到了这篇文章,但它似乎已经过时了:tableView section headers disappear SWIFT。 以下是我的header视图代码:

  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
  }

也许不太相关,但为什么不在第0节的标题高度中返回0呢?为什么要返回非常小的、几乎为0的值,而不是直接返回0呢? - rmaddy
我尝试过了,但并没有什么区别。 - SwiftyJD
1
我还建议您使用一个更有用的、非零初始框架来创建您的头视图。 - rmaddy
1个回答

4
当表格的UITableViewStyle属性设置为UITableViewStylePlain时,标题栏才会保持固定不动。如果将其设置为UITableViewStyleGrouped,则标题栏会随着单元格一起向上滚动。
因此,如果您想要固定在顶部的标题栏,则需要将UITableViewStyle设置为UITableViewStylePlain。
如果您想要与单元格一起向上滚动,则需要将UITableViewStyle设置为UITableViewStyleGrouped。

3
我的 UITableViewStyle 是 Plain,当滚动一行后,表头会消失。 - htafoya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接