collectionview global header does not push cells down and stays on top instead

Published

I have a collection view header (blue) and cells (red). I want to be able to show/hide header programmatically, however when I show the header programatically it appears on top of the cell (or makes scrollview go down a bit). I would like the header to push the whole scrollview down, so I wouldn’t have to scroll up after clicking "Toggle header".

enter image description here

I tried very hard to reproduce minimal code for the issue which is below. Please share any insights.

struct Section: Hashable {
    var items: [Int]
}

class ViewController: UIViewController {

    var collectionView: UICollectionView!
    var dataSource: UICollectionViewDiffableDataSource<Section, Int>?
    
    var showHeader = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: createCompositionalLayout())
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        collectionView.backgroundColor = .systemBackground
        
        collectionView.register(CellView.self, forCellWithReuseIdentifier: "cellId")
        collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerId")
        
        view.addSubview(collectionView)

        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        
        createDataSource()
        addData()
    }

    func createCompositionalLayout() -> UICollectionViewLayout {
        // layout for cell
        let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in
            let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))
            let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)
            layoutItem.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 0, bottom: 10, trailing: 0)
            let layoutGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(200))
            let layoutGroup = NSCollectionLayoutGroup.vertical(layoutSize: layoutGroupSize, subitems: [layoutItem])
            let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
            return layoutSection
        }
        
        let config = UICollectionViewCompositionalLayoutConfiguration()
        
        if showHeader {
            let layoutSectionHeader = createGlobalHeader()
            config.boundarySupplementaryItems = [layoutSectionHeader]
        }
        
        layout.configuration = config
        return layout
    }
    
    func createGlobalHeader() -> NSCollectionLayoutBoundarySupplementaryItem {
        let layoutSectionHeaderSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(50))
        
        let layoutSectionHeader = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: layoutSectionHeaderSize, elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)
        layoutSectionHeader.pinToVisibleBounds = true
        
        return layoutSectionHeader
    }
    
    func createDataSource() {
        dataSource = UICollectionViewDiffableDataSource<Section, Int>(collectionView: collectionView) { collectionView, indexPath, item in
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as? CellView else { fatalError("Unable to dequeue ") }
            cell.button.addTarget(self, action: #selector(self.onButtonClick), for: .touchUpInside)
            return cell
        }
        
        dataSource?.supplementaryViewProvider = { (collectionView, kind, indexPath) in
            guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as? HeaderView else { return nil }
            return header
        }
    }
    
    @objc func onButtonClick() {
        print("toggle")
        showHeader.toggle()
        collectionView.collectionViewLayout = createCompositionalLayout()
        collectionView.layoutIfNeeded()
    }
    
    func addData() {
        var snapshot = NSDiffableDataSourceSnapshot<Section, Int>()
        var sections: [Section] = []
        sections.append(Section(items: [0,1,2,3,4,5,6,7,8,9,10,11,12]))
        
        snapshot.appendSections(sections)
        
        for section in sections {
            snapshot.appendItems(section.items, toSection: section)
        }
        
        dataSource?.apply(snapshot)
    }

}

class CellView: UICollectionViewCell {
    let button = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .red
        
        addSubview(button)
        button.setTitle("Toggle header", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.topAnchor.constraint(equalTo: topAnchor).isActive = true
        button.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class HeaderView: UICollectionReusableView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .blue
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Source: Ios Questions

Answers

I think you need to embed the collection view and a regular view(that you will use as a header) in a Stack View, and programmatically hide and show the header view. This will make the collectionView expand in the stack view when the header is hidden and vise-versa. I would completely abandon the UICollectionReusableView header view. So the view hierarchy would look something like this:

  • StackView
    • HeaderView
    • CollectionView

I hope I explained myself clear enough.


Brett Quitzon

Leave a Reply

Your email address will not be published. Required fields are marked *

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq