Scroll to UICollectionView header

Swift Language

Scroll to UICollectionView header in Swift


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


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.


Share These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Twitter
  • LinkedIn
  • email
  • DZone
  • Slashdot
  • Reddit
  • Google Bookmarks
  • Digg
  • StumbleUpon
This entry was posted in Swift and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.


  1. Tim
    Posted December 25, 2015 at 3:25 pm | Permalink


    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,


  2. Pratik
    Posted January 24, 2017 at 3:52 am | Permalink

    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)

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">