Category

Scroll to UICollectionView header

Swift Language

Scroll to UICollectionView header in Swift

Introduction

One of the things that the UICollectionView lacks is the UITableView’s index title capability. You have to roll your own with the UICollectionView. I’ll leave that UI frob to you, but this quick post will show you how to scroll to show a section header.

Table of Contents

How to

Here is the first cut at scrolling to the second section (section 1). The problem is, it scrolls to the first item and the header is not shown. If that’s what you want, you can stop reading.

As usual, the “answers” at StackOverflow are mostly in the weeds. I don’t want to get locations directly from the layout delegate for example.

What you want to do is to ask the collection view for the layout attributes for your header view.

You can do this with a single function call:

You can then use the attribute.frame property to determine the header’s location. With that in hand, you can call setContentOffset() to scroll.

Table of Contents

Summary

Don’t mess around with doing the math yourself. Ask the collection view for the header’s attributes and use that frame to scroll.

Here is a Gist.

Resources

3 thoughts on “Scroll to UICollectionView header”

  1. Hi,

    Awesome tutorial about the CollectionView header scrolling! When I try to add your example, my CollectionView adds another header. How can I resolve this?

    Kind Regards,

    Tim

  2. it helped me. thanks for the sort tutorial, i’ve used
    let cv_attribute = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: IndexPath.init(item: 0, section: 0))
    collectionView.scrollRectToVisible((cv_attribute?.frame)!, animated: true)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.