从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。
这里有一个例子:
tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。
有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?
更新(回答):
在iOS 11及更高版本中:
tableView.contentInsetAdjustmentBehavior = .never
当你使用UITableView.Style.grouped或UITableView.Style.InsetGrouped时,如果没有“tableview header”,tableview将自动添加一个顶部inset填充到“section header”,修复很简单:
self.tableview.tableFooterView = UIView(frame: CGRect.init(origin: .zero, size: CGSize.init(width: tableview.frame.size.width, height: 1)))
self.tableview.tableHeaderView = UIView(frame: CGRect.init(origin: .zero, size: CGSize.init(width: tableview.frame.size.width, height: 1)))
如果你使用uitableview。style。plain
self.tableview.contentInsetAdjustmentBehavior = .never
一般来说就足够了
iOS 15的解决方案:
if #available(iOS 15.0, *) {
tableView.sectionHeaderTopPadding = 0
}
修正:在整个项目中修正:
if #available(iOS 15.0, *) {
UITableView.appearance().sectionHeaderTopPadding = 0
}
更多详细信息:在iOS 15中,表视图头部上有额外的填充
注意:这只适用于UITableView.Style.plain。
我遇到了同样的问题,但是tableView在tableView单元格中。
上面的无数答案都不起作用。
一个非常奇怪而简单的东西起了作用:
-在为tableView分配委托之前,放置估计的高度!!
override func awakeFromNib() {
super.awakeFromNib()
tableView.estimatedRowHeight = 58
tableView.estimatedSectionHeaderHeight = 45
tableView.estimatedSectionFooterHeight = 10
tableView.dataSource = self
tableView.delegate = self
}
将估计放在委托分配之后,导致我的内部tableView在标题上方有一个奇怪的空白。
我希望它能帮助到这里的人。
Swift 4代码:
对于没有section header的tableview,你可以添加以下代码:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
你会得到标题间距为0。
如果你想要一个特定高度的头文件,传递该值:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return header_height
}
和viewForHeaderinSection委托的视图。