How to implement Page Control in SwiftUI on WatchOS

Implementing PageControl View to your SwiftUI project using GeometryReader and DragGesture

Federico Rotoli
SwiftUI
3 min readJan 24, 2020

--

SwiftUI on WatchOS doesn’t have a native Page Control, in this article I’m going to teach you how to implement that component in your project.

Why should I use Page Control on WatchOS?

You should have already seen that, on WatchOS, there are only two ways to show another view: NavigationLink and Sheets. But what we need to do if we want another way? If we want to make a more user-friendly application probably a PageControl is the best solution. With that component, you can have two different views in one display separated by a very simple slide gesture.

The solution

Well, now let’s take a look at how we effectively implement that component to our project. First of all, we need to set up our PagerManager View: the goal of this view is to handle the navigation in the various views and to make them better by adding a simple animation linked to the gesture.

Now let’s check what happens inside the code:

  1. After the declaration of all the variables that we need in the view, we can see the initializer: where we set each variable to the value that you are going to write in the ContentView (you can find it a little below in the article).
  2. Let’s go ahead with the declaration of the slide gesture and, inside the body of our view, we use a GeometryReader to handle the user interaction and the size of the displayed frame.
  3. In the property .gesture of the GeometryReader, there is the main process that allows us that interact with the display; retrieving from the user the DragGesture and updating a stored value depending on the length of the movement. At the end of the movement, we call .onEnded for storing the value that checks the offset of the PagerManager that refers to the initial value, setting the new index (if possible).
Swipe Gesture on WatchOS

After that, we need to call this View in the main ContentView and specify the number of pages setting up the variable that checks the current index.

In this sample code you can see two main parts to focus on (after the first declarations of the variable for taking the current page index):

  1. The first one is the implementation of the View “PagerManager followed by the number of pages and the variable linked to the current index. In the braces of PagerManager, you need to call the Views that are going to represent each page of the application.
  2. The second one is the creation of a Horizontal Stack with two Circle functions which is a rude way to represent the effective PageControl. With the first variable declared we know when each circle needs to change its color.

--

--

Federico Rotoli
SwiftUI
Editor for

TEKny Co-Founder | Mobile Developer | Tech Addicted