Reproducing Snapchat’s Navigation on iOS — Part 1
Who doesn’t know Snapchat? Even if you’re not a user, I’m pretty sure you will have heard about this app! When I first discovered Snapchat, I instantly fell in love with the app navigation, and how immersive and natural it is.
I’m not the first developer to reproduce Snapchat navigation, and you can find many external libraries which do this for you. But I wanted to create an in-depth look into developing Snapchat’s navigation. If you are here, you might want to try implement it by your own and check what’s under the hood.
The whole idea for navigating app views is based on gestures. You can go from the central (camera) view, to every other screen by swiping in any direction. In this part we will focus on the horizontal flow axis as a warm up.
You can try achieve this effect with UIPageViewController, but in my opinion that’s a waste of time; in the end one way or another you will need to adopt a delegate of scrollView. It’s like using a sledgehammer to crack a nut.
I decided to add UIScrollView and set needed constraints programmatically (remember to add top and bottom constraints equal to superView, not the safe area, if you don’t want to see blank spaces on iPhone X family screens).
Next up, we want to add view controllers to our scroll view.
To keep codebase clean, we can implement this extension with proper factory methods.
What we have done here:
- This part of code models the behavior of scrollView, which we can set it as fileprivate, as we don’t want to make it accessible by every scrollView in the app
- Created internal function for adding view controllers as children
- Set the width and height to fill the whole screen
- Calculated the position on x axis for enumerated view controllers
- Set proper content size and content offset
- Added extension for fitting views into containers
Let’s go back to our main view controller, where you can set snapchat navigation with code:
Done! Once you have an idea of how it is working, it’s not that hard to implement. You might even be familiar with it thanks to other tutorials, but we need this for the next step, which is a bit more challenging and interesting in my opinion.