SwiftUI 2.0 is here! Following WWDC20, loads of new APIs and features were announced to come up in iOS 14. After only one year of existence, Apple has bet on this framework to support its new iOS release’s major features, such as Widgets and App Clips. This gives developers the opportunity we’ve been looking for: an excuse to start implementing SwiftUI views in our production code.
New in iOS 14, TabView
comes with a new modifier tabViewStyle
and a PageTabViewStyle
. This is the closest to a native pager in SwiftUI. The pagination is horizontal, single-page and elements take up 100% of their container’s frame:
https://gist.github.com/fermoya/9bdb04117bc88863c273bb7645f69636
This works just fine for some cases, but what about more advanced behavior? What if we were to perform some kind of operation when page three shows up? Can we partially show the side elements? All this is and more is possible with SwiftUIPager.
In the next few sections, I’ll introduce you to SwiftUIPager and leverage some of its potential. We’ll be building an app to help me choose a cat. I’ve created a repository to store the final result. Additionally, I’ll be sharing gist links in the image captions.
Let’s create a simple paged scroll with SwiftUIPager. You just need to use your favorite package manager and follow the installation instructions. Manual installation is also supported.
Note:_ although this tutorial has been written using Xcode 12b3, SwiftUIPager supports iOS 13+. If your App supports lower iOS versions, see the legacy installation guide._
I’m using Pager
to wrap a collection of AsynImage
to display cats images from The CatAPI:
https://gist.github.com/fermoya/68d5e4bb8889802fa16fd4a293f3f3e8
Just like that, we’ve managed to achieve the same behavior as by using TabView
. However, SwiftUIPager offers much much more.
Pager
Let’s customize the gallery a little bit:
https://gist.github.com/fermoya/11d417209e5413b17fe505c67d426b08
What’s happening here?:
vertical
transforms Pager
into a vertical pager.interactive
adds a beautiful scale effect to unfocused pages.itemSpacing
adds some space between the elements and itemAspectRatio
modifies the size of the page.padding
insets the content on the non-scrollable axis.alignment(.justified)
keeps pages centered within the scrollable area.#ios-app-development #sofware-engineering #programming #swiftui #ios