我使用UITableView来布局内容“页面”。我使用表视图的标题来布局某些图像等,我更喜欢它,如果他们没有浮动,但保持静态,因为他们做的时候,风格设置为UITableViewStyleGrouped。

除了使用UITableViewStyleGrouped,有办法做到这一点吗?我想避免使用分组,因为它增加了我所有的单元格的边缘,并要求为每个单元格禁用背景视图。我想完全控制我的布局。理想情况下,它们应该是“UITableViewStyleBareBones”,但我在文档中没有看到这个选项…

非常感谢,


当前回答

你可以通过在tableview delegate类中实现viewForHeaderInSection方法轻松实现。这个方法期望一个UIView作为返回对象(这是你的头视图)。我在代码中也做了同样的事情

其他回答

代码片段仅为第一部分显示粘头。其他的节头将与单元格一起浮动。

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    if section == 1 {
        tableView.contentInset = .zero
    }

}

func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
    if section == 0 {
        tableView.contentInset = .init(top: -tableView.sectionHeaderHeight, left: 0, bottom: 0, right: 0)
    }
}

实现这一点的一个可能更简单的方法:

objective - c:

CGFloat dummyViewHeight = 40;
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, dummyViewHeight)];
self.tableView.tableHeaderView = dummyView;
self.tableView.contentInset = UIEdgeInsetsMake(-dummyViewHeight, 0, 0, 0);

迅速:

let dummyViewHeight = CGFloat(40)
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
self.tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)

分段标题现在将像任何常规单元格一样滚动。

忽略XAK。如果你想让你的应用有机会被苹果接受,就不要探索任何私有方法。

如果您正在使用Interface Builder,这是最简单的。你可以在视图的顶部(图像所在的位置)添加一个UIView,然后在下面添加你的tableview。IB应相应地调整其大小;也就是说,tableview的顶部接触到你刚刚添加的UIView的底部,它的高度覆盖了屏幕的其余部分。

这里的想法是,如果UIView不是表格视图的一部分,它不会随着tableview滚动。即忽略tableview头。

如果你不使用界面构建器,它会更复杂一些因为你必须为tableview获得正确的定位和高度。

也许你可以在tableView上使用scrollViewDidScroll 并根据当前可见头更改contentInset。

它似乎适用于我的用例!

extension ViewController : UIScrollViewDelegate{

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard   let tableView = scrollView as? UITableView,
            let visible = tableView.indexPathsForVisibleRows,
            let first = visible.first else {
            return
        }

        let headerHeight = tableView.rectForHeader(inSection: first.section).size.height
        let offset =  max(min(0, -tableView.contentOffset.y), -headerHeight)
        self.tableView.contentInset = UIEdgeInsetsMake(offset, 0, -offset, 0)
   }
}

警告:这个解决方案实现了一个保留的API方法。这可能会阻止苹果批准该应用程序在AppStore上发布。

我已经在我的博客中描述了使节头浮动的私有方法

基本上,你只需要子类化UITableView并在它的两个方法中返回NO:

- (BOOL)allowsHeaderViewsToFloat;
- (BOOL)allowsFooterViewsToFloat;