分组UICollectionView有额外的35像素的顶部填充



我正在创建一个grouped UICollectionView,似乎顶部有35像素的额外填充在顶部,我不知道如何摆脱。

看来这也是UITableView的问题,我在这里和这里发现了一些问题来解决它,但这些解决方案不适用于UICollectionView

下面是我如何初始化UICollectionView:

var listConfig = UICollectionLayoutListConfiguration(appearance: .grouped)
UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewCompositionalLayout.list(using: listConfig))
// More autolayout constraints code later

到目前为止,为了解决这个问题,我一直在对topAnchor应用-35常数,但这并不适用于所有情况(当我想要在同一视图中直接在上面的东西时)。

我也尝试了listConfig.headerTopPadding = 0,但没有成功。

我怎样才能去掉这个额外的顶部填充?(附带问题……为什么会存在?)

正如你在这里提到的

collectionView。contentInset = UIEdgeInsets(top: -35, left: 0, bottom: 0, right: 0)

我认为这不是一个很好的解决方案,真正的原因是由.grouped产生的。控制整个contentView的偏移量,contentInset不应该用来偏移header的效果(如下所示)。


当你指定UICollectionLayoutListConfiguration.grouped模式下,如果没有任何其他代码,您的listConfig默认意味着listConfig.headerMode = .nonelistConfig.footerMode = .none。collectionView将为每个节生成一个页眉和一个页脚。

35像素来自你的部分标题的高度。在这种情况下,我猜你只有一个部分,正如你所看到的,你必须在底部有相同的额外填充。

解决方案

1, listConfig.headerMode = .firstItemInSection

最方便最简单的方法

当您使用此头模式时,UICollectionViewListCell对象作为节中的第一个项目自动使用头外观。在配置数据源时,请确保考虑到这样一个事实,即节中的第一个项(索引0处)表示标题,而节中的实际项从索引1处开始。

2, listConfig.headerMode = .supplementary

你可以完全自定义标题UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if (kind == UICollectionView.elementKindSectionHeader) {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "your headerIdentifier", for: indexPath)
            ... // do some custom things
            return header
        }
        return UICollectionReusableView()
    }

别忘了这个

collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "your headerIdentifier")

当我写这个问题的时候,我又找到了一个堆栈溢出的答案,这最终给了我一个适合我的答案。我使用了方法4:

collectionView.contentInset = UIEdgeInsets(top: -35, left: 0, bottom: 0, right: 0)

这将我的内容向上移动,并允许我将内容放在我的collectionView之上,而不会出现任何问题。

最新更新