从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。
这里有一个例子:
tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。
有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?
更新(回答):
在iOS 11及更高版本中:
tableView.contentInsetAdjustmentBehavior = .never
自我。automcallyadjustsscrollviewinsets = NO;
这在iOS 11中已弃用,所以你应该使用new属性
contentInsetAdjustmentBehavior在你的代码中,它应该修复这个问题。
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
在UIScrollView中添加了一个名为contentInsetAdjustmentBehavior的新属性,用于确定调整内容偏移量
对于第一部分,我们需要像这样设置tableHeaderView:
tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: .leastNonzeroMagnitude))
对于其他section,我们应该像这样设置highightforfooterinsection:
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return .leastNonzeroMagnitude
}
根据苹果的文档:
当将视图分配给此属性时,将该视图的高度设置为
一个非零值。表视图只尊重您的高度
视图的框架矩形;它调整你的头视图的宽度
自动匹配表视图的宽度。
斯威夫特5
如果你有一个分组UITableView,你想要一个tableHeaderView:
在将视图分配给tableView之前。tableHeaderView,设置该视图的高度为一个非零值,例如:
// Set the initial height of your custom view to the smallest value
myTableHeaderView.frame.size.height = .leastNonzeroMagnitude
// Assign your custom view to the header view
tableView.tableHeaderView = myTableHeaderView
// Set width constraint, height should grow based on your view.
tableView.tableHeaderView!.widthAnchor.constraint(equalTo: tableView.widthAnchor).isActive = true
不需要使用contentInsets或处理委托方法。