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

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

非常感谢,


当前回答

一个棘手的方法是为标题添加一个空部分。因为section没有单元格,所以它根本不会浮动。

其他回答

Swift 3+

简单地使用UITableViewStyleGrouped并将页脚的高度设置为0,如下所示:

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return .leastNormalMagnitude
}

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

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

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

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

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

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)
    }
}

如果你不介意使用UICollectionView,这也可以在iOS 13.0+中使用UICollectionView列表配置并使用headerMode设置为. firstiteminsection来实现。

override func viewDidLoad() {
    super.viewDidLoad()
    var config = UICollectionLayoutListConfiguration.init(appearance: .plain)
    config.headerMode = .firstItemInSection
    let listLayout = UICollectionViewCompositionalLayout.list(using: config)
    self.collectionView.collectionViewLayout = listLayout
}

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

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)

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