UICollectionViewFlowLayout 子类 Sticky 和 ​​Stretchy header

UICollectionViewFlowLayout subclass Sticky and Stretchy header

我使用带有独特部分的 UICollectionView 来拆分大视图的逻辑。这个有一个 HeaderView 和一张图片,我试着让这个 header 有粘性和弹性(当你向下滚动时 header 变小直到只是一个条并坚持顶部,当您向上滚动并弹跳时,header 会回到图片并拉伸)。

我阅读并观看了许多教程并尝试自己实现,但每次都发生相同的行为:

单元格不再滚动,header 向下滑动。

我每次打电话也是:

collectionViewLayout.invalidateLayout()

collection 视图无动画滚动回顶部。

下面,只有弹性部分!

这里是我的 CustomCollectionViewFlowLayout 代码:

class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let layoutAttributes = super.layoutAttributesForElements(in: rect),
            let collectionView = collectionView else {
            return nil
        }

        let offset = collectionView.contentOffset
        if offset.y < 0 {
            let deltaY = abs(offset.y)
            for attributes in layoutAttributes {
                if attributes.representedElementKind == UICollectionElementKindSectionHeader {
                    var frame = attributes.frame
                    frame.size.height = max(0, headerReferenceSize.height + deltaY)
                    frame.origin.y = frame.minY - deltaY
                    attributes.frame = frame
                }
            }
        }

        return layoutAttributes
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

}

这里是我如何 link 使用 CollectionViewController 的:

override func viewDidLoad() {
    super.viewDidLoad()

    if let flowLayout = collectionViewLayout as? PINPropertyDetailsCollectionViewFlowLayout {
        let side = collectionView?.frame.width ?? 375
        flowLayout.headerReferenceSize = CGSize(width: side, height: side)
        flowLayout.estimatedItemSize = CGSize(width: side, height: 1)
    }
    collectionView?.contentInset = UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0)
}

我尝试使用:

flowLayout.sectionHeadersPinToVisibleBounds = true

也没有更多结果:不再滚动(单元格或 header)...

我使用 Xcode 9(测试版 4)编码 iOS 9 和 10。

感谢反馈:)

我已经通过实现 UICollectionViewDelegateFlowLayout 和方法 collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize.

解决了这个问题

如果没有固定的项目尺寸(直到现在我使用的是自动尺寸),弹性效果显然是不可能的