How to implement a horizontally-scrolling collection view with a header on top?

Viewed 2493

I want to have a collection view that scrolls horizontally, but I also want it to have a header on top of and to the right. I've tried implementing this as I would a vertically-scrolling collection view, and the header ends up to the left of the first cell.

Here is how I dequeue the header:

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: identifier, for: indexPath) as! HeaderView
        header.setWidth(to: headerWidth)
        return header
    }

Size of the header:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 12)
    }

Apart from that, the only other properties I initialize are the scroll direction and insets of the collection view

1 Answers

Headers positions : are in the Top of the section in case of scrolling vertically and in the left of the section in case of horizontally scrolling , So it's normal that it's showing in the left of the section in your case .

If you want to display your reusable view in the right of every section You can use UICollectionView.elementKindSectionFooter instead .

But if you want to display your reusable view between every section , You can set the size of header view in the very first section to .zero .

You can manipulate in every header view size with referenceSizeForHeaderInSection function like so:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0 {
            return .zero
        }
        return CGSize(width: collectionView.frame.width, height: 12)
    }

In this case i removed (technically not removed but hide) the first header in the left , Which is in the first section , But you can set the size for every header .

Related