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

Find the second article which extends on this one here:

The idea I had when I decided to write this short article was that I a) wanted to share some of what I learned and b) these short articles helped me a lot when learning to code.

In this article, you will learn in two easy steps how to implement your own custom view router with SwiftUI. This way you can create e.g. custom tab bars.

Those of you that come from React will see that is similar to react-router.

In the first step, you create an enum that holds all the possible views as cases. Imagine a home view that has a gear symbol for settings in the navigation bar and three buttons in the tab bar. In this case, you will need four different cases.

In the second step, you implement your newly created enum in a view. For this create a new view and name it CustomPageView. You will have a property that is wrapped in @State. This way you will publish any changes made to the property to your view, that works as a subscriber in that case.

  1. Set your variable to be the view you want to be displayed when the view shows up. I made the variable private, which is not really necessary here but it’s just a habit for me.
  2. Instead of putting content directly into your body, you provide a switchthat shows content based on the variable created above.
  3. Each case shows its own content. We don’t have any functionality to change the view here yet.

You should now have a first overview of how you can create a custom view router with two simple steps with SwiftUI. In the next articles, I will show, how you can change the view, will show different use cases and will apply animations to it.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store