Create your custom view router with SwiftUI (2/X)

This article is the second part that builds upon the basics that were introduced in Create your own custom view router with SwiftUI (1/X).

In this second article we will extend the basics from the first article on apply some gestures to our project.

SwiftUI Gestures

We can declare a DragGesture either with no parameters, or we can pass minimumDistance and/or coordinateSpace. This way we can create a gesture with a minimum dragging distance and the coordinate space of the gesture's location. The coordinateSpace can either be .local, .global or named(). In this example we're using .local as we want only to recognize the local gesture per view.

Extending The Basics

This way we provide functions that can be accessed in our views, as we already reference to ViewRouter.

Implementing The Changes

  1. We introduce another variable that holds a Bool value. That value either is true or false, corresponding to the SettingsView being shown or hidden.
  2. We extended our views, as they not accept two parameters. They do accept our as a Binding as well as showSettings as a Binding. How this is exactly implement, will be shown down below.
  3. The settings view is the only view that is displayed in another way. It is shown as a sheet, which means, that it slides into view from the bottom edge.

Changes Made to Individual Views

  1. We declare our new Binding in the same way we did with page.
  2. In this simple example we modify our Text with a gesture, that changes either page or showSettings based on the gesture done. To do so, we introduce the .gesture() modifier along with DragGesture() as described further above. We also want some code to be triggered after the gesture, hence the .onEnded() modifier.
  3. Next we define what do to based on a value provided by the gesture. Actually it's quite simple: if the width is smaller than zero, and the height is somewhere between -30 and 30, we assume a swipe to the left. We want then to go to the next page. Don't get confused by the second pair of paratheses, we need to put them there, because we didn't create an instance of ViewRouter but only reference to the type itself.
  4. The last step is to set showSettings to true, if we swipe up.