How to create onboarding with Compositional Layout
Utilizing Compositional Layout to create onboarding flow. Full code example is available.
Published: Feb. 5, 2021 Sponsored I want a Press KitIn another shorter post about CollectionView Compositional Layout I would like to show how you can use this API to create onboarding flow.
Onboarding is the (often) multi-page welcome screen for new users of your app. It is useful when you really want to explore the app features. Users typically can go back and forth between the pages and get a feel about the app features.
There are of course many ways of creating such flow, but if you already have experience with CollectionViews and Compositional Layout I think it makes sense to use it for this also.
Since we want to have fullscreen "cards" with horizontal scroll, we are going to define just a single NSCollectionLayoutItem
wrapped in a NSCollectionLayoutGroup
that gives its a bit of padding.
Here is the relevant code:
func createLayout() -> UICollectionViewLayout {
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)))
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(0.95))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
group.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 15, bottom: 5, trailing: 15)
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .paging
return UICollectionViewCompositionalLayout(section: section)
}
With the contentInsets
on the group we can create a nice paddings. And the horizontal scrolling is achieved by setting the orthogonalScrollingBehavior
. I think .paging
work pretty well here.
And here is the layout in action:
For better experience I have disabled the vertical bounce on the CollectionView:
collectionView.alwaysBounceVertical = false
And that's it! Onboarding done. The complete code is available in my example project.
However there is currently an issue with scrollToItem
method that does not work on iOS 14, when any kind of paging is enabled. This can be really problematic if you want to let user skip the steps and go to last onboarding page. If you don't then this works pretty well.
Uses: Xcode 12 & Swift 5.3