There are many situations when you’d like to add a header and footer to a UICollectionView component, in Swift. Regardless whether it’s a simple title or a more advanced view, UICollectionView supports headers and footers out of the box, without too much boilerplate code.

The main advantages of using this approach are that the alternatives are pretty messy. You’re also getting other benefits:

  • Both header and footer are natively part of the collection view, so they will be part of the scroll view as well.
  • You can use any UICollectionReusableView subclass, so you can customize the header and footer as you wish
  • You can register the nib for any UICollectionReusableView subclass on the collection view, so you’re able to use Interface Builder to design your header and footer views
  • These views are recycled similar to how the cells’ views are recycled, so this approach is performant

Without further ado, to add a header and footer view to a collection view, in Swift, we need to take advantage of the supplementary element concept, which consists of a few different types of reusable views, in addition to the regular UICollectionViewCells. Here’s a simple implementation, that only overrides an optional method on the UICollectionViewDataSource protocol:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if (kind == UICollectionElementKindSectionFooter) {
        let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "CartFooterCollectionReusableView", for: indexPath)
        // Customize footerView here
        return footerView
    } else if (kind == UICollectionElementKindSectionHeader) {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "CartHeaderCollectionReusableView", for: indexPath)
        // Customize headerView here
        return headerView
    }
    fatalError()
}

The implementation is pretty straightforward. We are checking for the supplementary element’s kind that’s currently being requested through the data source, and provide each reusable view as appropriate. Keep in mind that you have to obtain the views that are being returned by calling “dequeueReusableSupplementaryView(ofKind: )” on the collection view itself. Not doing so will result in a crash.

We are using this Swift code to implement the check out button of our Restaurant app template, as a UIButton which lives in the footer reusable view of the collection view displaying the shopping cart items.

UICollectionView swift header footer collection view scrollable

Categories: Swift programming

Leave a Reply

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