tableView.headerView(forSection:0)的高度为零
问题描述:
我试图改变标题视图的高度,因为用户滚动跟随this tutorial。但是,当我尝试访问self.songsTable.headerView(forSection: 0)?.frame.size.height
(因此我可以更新标题视图的高度)时,值为零,调试器告诉我“标题视图没有高度”。我使用heightForHeaderInSection
和viewForHeaderInSection
以编程方式创建了我的标题视图。tableView.headerView(forSection:0)的高度为零
代码
class SongsViewController {
var currentHeaderHeight: CGFloat = 136
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//Throws error
guard let currentHeaderHeight = self.songsTable.headerView(forSection: 0)?.frame.size.height else {
print("header view has no height")
return
}
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return currentHeaderHeight
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.frame = CGRect(x: 0, y: 0, width: Screen.width, height: maxHeaderHeight)
return headerView
}
}
答
这可能只是缺少您的代码段,但你设置你的viewController作为TableViewDataSource?
class SongsViewController: UIViewController, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
songsTable.dataSource = self
}
// ... the rest of your code ...
}
+0
yupp我已经做到了。也许我打电话错误的func来获取该部分的标题视图? – Alex
如果没有看到完整的代码,这有点难以调试。一些想到的东西 - 什么是currentHeaderHeight?它可能是0吗?你有任何部分(numberOfSections)?您的调试器打印是因为songsTable.headerView(forSection:0)是否为零? – cloudcal
@cloudcal我更新了我的代码。 currentHeaderHeight最初设置为136.'numberOfSections'为1.我不确定为什么'songsTable.headerView(forSection:0)'是扼杀,即使我可以在模拟器上看到标题 – Alex
@Alex,嗨,你发现了吗?出这个零问题的理由? – 0xa6a