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.

How many pages do you want to have?

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.

Implement in a view

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.

--

--

--

Product manager @ day, Coder @ night.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SwiftCurrent versus The Coordinator Pattern

Xcode with a side-by-side comparison of SwiftCurrent and the Coordinator pattern.

Zara replica — part 4

How to be better at iOS development?

Controlling Your Phone From the Cloud

Using SwiftCurrent with MVVM Part 2

CocoaPods adding SwiftCurrent with a pod named SwiftCurrent slash SwiftUI.

Custom Gesture Recognizers in iOS

Who call me ?

Apple WWDC 2020 -Part 2

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
Roman Zuchowski

Roman Zuchowski

Product manager @ day, Coder @ night.

More from Medium

MVVM in SwiftUI

Goodbye NSPredicate, hello Realm Swift Query API

How to preview UIViewControllers using SwiftUI

Drawing Vectors using UIBezierPath in Swift