Before iOS 13, if you wanted to have a vertical collection view with horizontally scrolling sections it required embedding a scroll view inside the collection view cell, passing the model around, handling touch events, a lot of delegation, and complicated logic. With UICollectionViewCompositionalLayout
all of those problems fading away. Apple gave us orthogonalScrollingBehavior
.
We will build our new section using code from my last post.
Let's start with our model. I want to display a horizontally scrolled section displaying just letters. Modify model class by adding new var:
Now simple cell, just label for letter:
So far so good. Now, adjust our view controller, it needs to know about the new section and new cell.
In func prepareCollectionView()
register new cell:
Our UICollectionViewDataSource
have to return two sections and handle cell preparation:
We are almost there. The last thing is to modify our layout:
The biggest changes are:
- Now instead of returning one section, we have a factory method returning different sections layouts depending on the section number
- New section layout. There is nothing special about it at the first glance. One item, one simple group. Biggest change is
section.orthogonalScrollingBehavior = .groupPagingCentered
- setting this makes the section scroll perpendicularly to the main axis of our collection view. And this is the only thing needed to make such a section work. No embedding, no delegation, just one simple line of code!
And the effect:
The full code can be found here.