Stretchy Header for UICollectionView

三世轮回 提交于 2021-02-07 19:15:18

问题


I am trying to create a stretchy header using a collectionview section header. There are a bunch of different ways to do this but I am just looking for the simplest and most straight forward method with clear insturctions on what to do. Has anybody seen a simple guide on doing this in Swift 3 or can you explain how this would be done here?

I don't think it should be that difficult. I would like to use the UICollectionViewDelegateFlowLayout and the ScrollviewDelegate becuase I think that would be the easiest way for it to be done.

Can I use the scrollViewDidScroll method to control height of the header as a user is scrolling. How would I change the height of the header manually? I know on the storyboard I can change it in the UICollectionView header size settings but how would I adjust it in code?


回答1:


With Swift 5 / iOS 12.3, you can override shouldInvalidateLayout(forBoundsChange:) and layoutAttributesForElements(in:) methods inside a UICollectionViewFlowLayout subclass in order to create a stretchy header in a UICollectionView. The following sample code shows how to implement those methods:

CollectionViewController.swift

import UIKit

class CollectionViewController: UICollectionViewController {

    let flowLayout = CustomFlowLayout()

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let collectionView = collectionView else { fatalError() }

        collectionView.alwaysBounceVertical = true
        collectionView.contentInsetAdjustmentBehavior = .always
        collectionView.collectionViewLayout = flowLayout
        collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView.register(HeaderReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeaderView")
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) as! HeaderReusableView
        return headerView
    }

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

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
    }

}

CustomFlowLayout.swift

import UIKit

class CustomFlowLayout: UICollectionViewFlowLayout {

    let idealCellWidth: CGFloat = 100
    let margin: CGFloat = 10

    override init() {
        super.init()

        sectionInsetReference = .fromSafeArea
        sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
        headerReferenceSize = CGSize(width: 0, height: 80)
        sectionHeadersPinToVisibleBounds = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func prepare() {
        super.prepare()

        guard let collectionView = collectionView else { return }
        let availableWidth = collectionView.frame.width - collectionView.safeAreaInsets.left - collectionView.safeAreaInsets.right - sectionInset.left - sectionInset.right
        let idealNumberOfCells = (availableWidth + minimumInteritemSpacing) / (idealCellWidth + minimumInteritemSpacing)
        let numberOfCells = idealNumberOfCells.rounded(.down)
        let cellWidth = (availableWidth + minimumInteritemSpacing) / numberOfCells - minimumInteritemSpacing
        itemSize = CGSize(width: cellWidth, height: cellWidth)
    }

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

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

        let offsetY = collectionView.contentOffset.y + collectionView.safeAreaInsets.top
        if let firstHeader = rectAttributes.first(where: { $0.representedElementKind == UICollectionView.elementKindSectionHeader && offsetY < 0}) {
            let origin = CGPoint(x: firstHeader.frame.origin.x, y: firstHeader.frame.minY - offsetY.magnitude)
            let size = CGSize(width: firstHeader.frame.width, height: max(0, headerReferenceSize.height + offsetY.magnitude))
            firstHeader.frame = CGRect(origin: origin, size: size)
        }

        return rectAttributes
    }

}

CollectionViewCell.swift

import UIKit

class CollectionViewCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .cyan
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

HeaderReusableView.swift

import UIKit

class HeaderReusableView: UICollectionReusableView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .magenta
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

Expected result:



来源:https://stackoverflow.com/questions/44446059/stretchy-header-for-uicollectionview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!