【问题标题】:UICollectionView sectionInsets not respected when using Header Cells使用标题单元格时不尊重 UICollectionView sectionInsets
【发布时间】:2020-01-15 21:34:48
【问题描述】:

我正在尝试创建一个包含标题单元格(动态大小)和一些“正常”内容单元格(也是动态大小)的集合视图。因此,collection view 初始化如下:

private lazy var timelineCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .vertical
        flowLayout.sectionInset = UIEdgeInsets(top: self.coloredTitleBarHeight, left: 0, bottom: 0, right: 0) // assume that coloredTitlebarHeight is a constant of 120
        flowLayout.estimatedItemSize = CGSize(width: self.view.frame.width, height: 10)
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0

        let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        cv.alwaysBounceVertical = true
        cv.contentInsetAdjustmentBehavior = .never 
        cv.backgroundColor = .clear
        cv.scrollIndicatorInsets = UIEdgeInsets(top: self.coloredTitleBarHeight - self.getStatusBarHeight(), left: 0, bottom: 0, right: 0)

        cv.delegate = self
        cv.dataSource = self
        cv.register(TLContentCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "content-header-cell")
        cv.register(TLContentCell.self, forCellWithReuseIdentifier: "comment-cell")

        return cv
    }()

collectionView 是 符合以下协议的 ViewController 的一部分:UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

然后,我使用以下代码创建一个标题单元格:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "content-header-cell", for: indexPath) as! TLContentCell

        cell.timelineContent = tlContentItem
        cell.delegate = self

        return cell
    }

最后但同样重要的是,常规单元的出队:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "comment-cell", for: indexPath)

        return cell
    }

输出:

collectionView 显示标题单元格以及项目单元格,但是,不应用部分 Insets。

如果您能就这种奇怪的行为向我提供任何建议,我将非常高兴。

【问题讨论】:

    标签: ios swift uicollectionview uikit uicollectionviewcell


    【解决方案1】:

    Section insets 仅应用于 UICollectionViewFlowLayout 中的内容。

    使用部分插图调整内容的边距

    部分插图是一种调整可用于布置单元格的空间的方法。 您可以使用 insets 在节的标题视图之后插入空格,并 在其页脚视图之前。您还可以使用 insets 在周围插入空格 内容的侧面。图 3-5 演示了插图如何影响 垂直滚动流布局中的一些内容。 source

    【讨论】:

    • 感谢您的回复。但是我怎样才能创建一个“上边距”呢?有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2013-10-17
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多