从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。
这里有一个例子:
tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。
有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?
更新(回答):
在iOS 11及更高版本中:
tableView.contentInsetAdjustmentBehavior = .never
下面的操作(Swift)解决了这个问题,但当你不需要头文件的时候,这是有效的。
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.min
}
如果你这样做,你将不得不放弃第一部分,并使用其他内容。
UITableViewDataSource实施:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return <number_of_data_sections>+1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// the first section we don't use for data
if section == 0 {
return 0
}
// starting from 1, there are sections we use
if section == 1 {
let dataSection = section - 1
// use dataSection for your content (useful, when data provided by fetched result controller). For example:
if let sectionInfo = myFRC!.sections![dataSection] as? NSFetchedResultsSectionInfo {
return sectionInfo.numberOfObjects
}
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dataIndexPath = NSIndexPath(forRow: indexPath.row, inSection: (indexPath.section - 1) )
// return cell using transformed dataIndexPath
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 1 {
// return your header height
}
return CGFloat.min
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 1 {
// return your header view
}
return nil
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// in my case, even when 1st section header was of zero heigh, I saw the space, an that was a footer. I did not need footer at all, so always gave zero height
return CGFloat.min
}
就是这样。模型不知道任何变化,因为我们在访问数据时转换了节号。
对于第一部分,我们需要像这样设置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
}
自我。automcallyadjustsscrollviewinsets = NO;
这在iOS 11中已弃用,所以你应该使用new属性
contentInsetAdjustmentBehavior在你的代码中,它应该修复这个问题。
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
在UIScrollView中添加了一个名为contentInsetAdjustmentBehavior的新属性,用于确定调整内容偏移量
我遇到了同样的问题,但是tableView在tableView单元格中。
上面的无数答案都不起作用。
一个非常奇怪而简单的东西起了作用:
-在为tableView分配委托之前,放置估计的高度!!
override func awakeFromNib() {
super.awakeFromNib()
tableView.estimatedRowHeight = 58
tableView.estimatedSectionHeaderHeight = 45
tableView.estimatedSectionFooterHeight = 10
tableView.dataSource = self
tableView.delegate = self
}
将估计放在委托分配之后,导致我的内部tableView在标题上方有一个奇怪的空白。
我希望它能帮助到这里的人。