Custom Paging UI in SwiftUI
Create animated index views with the new PageTabViewStyle
SwiftUI 2 introduced a new
TabView style called
PageTabViewStyle that enables developers to easily create horizontal Pagers (aka Paging) with dots at the bottom to show users where they are. This is the equivalent of
UIPageViewController from UIKit.
Today, we will cover how to use the new style for
TabView and how to create a custom
Using the new API is as simple as setting the new
Here, I have an array of colors — with each color being a page — and I am also tagging every
Color view with its desired index. The
TabView initializer has a
selection binding that represents the current page.
A couple of things to keep in mind:
- The paging dots are white and translucent. Therefore, if your background is also white, you won’t see them (tested on iOS/Xcode Beta 3).
- The contents of the
TabViewcannot be drawn over the safe area insets (Tested on iOS/Xcode Beta 3).
Creating a Custom IndexView
Now that we have the basics covered, we can quickly create any custom component to represent the current page and update it accordingly with our
currentIndex state property.
We are going to take a stab at making a more dynamic version of the system dots. This index component will present at most three dots and animate the insertion/removal as you swipe through the pages.
That’s quite a bit of code, so let’s go through it step by step:
shouldShowIndex() — Display only three dots or less (for the current page and its adjacent pages).
.scale() — Apply different styling to showcase which
Circle is focused.
.transition() — Animate the insertion and removal of each
Circle with opacity and scale.
.id(index) — Create unique
Circle instances for each index.
Now we just need to update
ContentView to make use of the new
- Add an implicit animation for every change that happens to the
- Overlay the new
IndexViewcomponent and plug in the necessary properties.
Making animations in SwiftUI was already insanely easy, and now with the new
TabView style, you can create any kind of index view! Stay tuned for my upcoming articles!
If you are feeling brave enough, I encourage you to try to make your own animations!