从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。

这里有一个例子:

tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。

有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

Swift3

如果你使用分组表,然后做以下事情。 这将删除顶部空间。

    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    self.tableView.tableHeaderView = UIView(frame: frame)
    self.tableView.tableFooterView = UIView(frame: frame)

如果你仍然得到这个问题,那么它将删除默认的内容偏移从顶部。

[永不设置内容插入] https://i.stack.imgur.com/fjxOV.png

其他回答

下面的操作(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
}

就是这样。模型不知道任何变化,因为我们在访问数据时转换了节号。

    if #available(iOS 15.0, *) {
        tableView.sectionHeaderTopPadding = 0
    }

放上这段代码,就可以了

这是在iOS 11和Xcode 9.1中通过Storyboard轻松修复的方法:

Select Table View > Size Inspector > Content Insets: Never

我有一个VC与容器在它(btw是一个导航控制器的一部分),并嵌入其中是一个TableVC。

选择我的TableVC,查看属性面板:

取消勾选自动调整滚动插入 取消检查顶部栏下的延伸边

然后我设置了容器相对于父视图的自动约束:

容器的观点。top = ParentView。顶边

这为我完成了以下任务:

保持桌面拉到顶部,但就在我的导航栏下面 刷新后,表返回到这个位置,而不是像以前那样在导航栏下向上+ 在实际的底部滚动表底部后,不缺它

我用这个设置进行了大量的试验和错误,但我最终发现了lekksi @移除UITableView单元格前的空白空间发布的这些小细节

在我的例子中,在Storyboard的原型可视化中有一个不需要的名为HeaderView的单元格,当我删除它时,一切都很好。