How to navigate between views in SwiftUI by using an @ObservableObject

Share on facebook
Share on twitter
Share on pinterest
Updated for Xcode 12 and SwiftUI 2.0 ✅

Hello and welcome to this tutorial! In this post, we will talk about how to navigate between views in SwiftUI (not using a NavigationView!). A concept that may sounds trivial but by understanding it deeply we can learn a lot about the data flow concepts used in SwiftUI.

This tutorial is an excerpt from our Interactive Mastering SwiftUI Book

In this tutorial, you will learn:

  • How to navigate between views without relying on a navigation view hierarchy
  • More advanced data flow techniques including ObservableObjects, @StateObjects and @EnvironmentObjects
  • Taking a first look at using animations in SwiftUI

In this part, we will learn how to navigate between views using a ObservableObject and @StateObject. In the next part, we look at how to accomplish the same behaviour more efficiently using an @EnvironmentObject and apply some nice navigation animations.

And here is what we are going to achieve at the end of this tutorial:

For learning how to navigate between different views in SwiftUI, it’s appropriate to start with an example that’s not too complex. Supposed we have an app with two different views. ContentViewA shows an Image view with a grumpy dog and a Button reading “Next”. The other view called ContentViewB shows an Image view with a happy dog and a Button reading “Back”.

You can download the starter project here:

Starter Project

We want to connect those views in a way that when we tap on the buttons we navigate back and forth. We could accomplish this using a NavigationView, but in this chapter, we don’t want to use such a navigation view hierarchy. Instead, we want both views to be independent of each other.

So let’s get started!

Creating a Mother View 👩‍👧‍👦

The first step is to create a mother view that hosts both Content Views as its subviews. For this purpose, create a new File-New-File-SwiftUI View and name it MotherView. In this view, we want to show either ContentViewA or ContentViewB depending on where the user navigated to. 

Important: Since our MotherView will “contain” the ContentViews, it must be the root view when the app launches. To set the MotherView as the root view, go into the NavigatinInSwiftUIApp.swift file and replace the ContentViewA inside the WindowGroup with an instance of our MotherView.

@main
struct NavigatingInSwiftUIApp: App {
    var body: some Scene {
        WindowGroup {
            MotherView()
        }
    }
}

Back to our MotherView.swift file: To keep track of the selected main view, we need to declare a State property. At default, we want to present ContentViewA as the first “page”. For this purpose, create a new Swift file called Helper.swift and insert the following enum.

enum Page {
    case page1
    case page2
}

Now, we can declare the State property in our MotherView and assign it to the page1 option of our Page enum.

struct MotherView: View {
    
    @State var currentPage: Page = .page1
    
    var body: some View {
        Text("Hello World")
    }
}

State properties are used for displaying views depending on the State’s data. Every time the State gets updated it triggers the view to rerender. If you’re not familiar with the concept of States in SwiftUI, we strongly recommend you to read this tutorial first, since it’s crucial for understanding the following concepts!

Depending on the Page assigned to the currentPage State, we want to either host ContentViewA or ContentViewB. Let’s implement this logic by inserting a switch-statement inside a VStack.

var body: some View {
    switch currentPage {
    case .page1:
        ContentViewA()
    case .page2:
        ContentViewB()
    }
}

Let’s run our preview simulator and take a look at it. Since our State is currently assigned to .page1, our first switch case is met and the ContentViewA gets hosted. Let’s change the page State to .page2 and see what happens.

Here we go! Because the State changed, our whole MotherView gets updated and the switch block gets executed again, this time showing us ContentViewB. So far, so good.

But we want to let the user change the currentPage State by tapping on the Buttons inside of ContentViewA and ContentViewB, respectively. Note that the Buttons are not part of the MotherView itself, so we need to create a “bridge” for accessing the MotherView’s currentPage Statefrom the outside; meaning that when, for instance, tapping on the “Next” Button of ContentViewA, we alter the Page assigned to the currentPage State of the MotherView for eventually navigating to ContentViewB.

We can achieve this by interjecting something called an ObservableObject into our MotherView – ContentViews hierarchy. 

ObservableObjects ?! 🤯

At this point, you are probably asking yourself: “What the heck are ObservableObjects?!”. Well, understanding this can be pretty tough but don’t worry, we will explain it to you in a simple way.

ObservableObjects are similar to State properties which you should already know. But instead of just rerendering at the body of the related view when the data assigned to the State changes, ObservableObjects are capable of the following things: 

  • Instead of variables, ObservableObjects are classes that can contain data, for example, a String assigned to a variable 
  • We can bind multiple views to the ObservableObject (in other words: we can make these views observe the ObservableObject). The observing views can access and manipulate the data inside the ObservableObject
  • When a change happens to the ObservableObject’s data, all observing views get automatically notified and rerendered similar to when the value assigned to a State changes

So, how could we use this functionality? Well, we can create an ObservableObject class that contains a variable indicating the current Page that should be displayed. Then we can bind our MotherView, our ContentViewA, and our ContentViewB to it. Then, we can tell our MotherView to show the corresponding ContentView depending on the Page assigned to the ObservableObject’s variable.

From the Buttons inside the ContentViews, we can update the Page assigned to the ObservableObject’s variable. This would cause all three observing views to update their bodies, including the MotherView. With this functionality, we can achieve that the MotherView will present show the correct ContentView depending on the selected Page!

Honestly, this seems a little bit abstract, but it should become clearer when applying the concept to our app.

Let’s create such an ObservableObject. To do this, create a new Swift file and call it ViewRouter.swift. Make sure you import the SwiftUI framework. Then create a class called ViewRouter conforming to the ObservableObject protocol.

import SwiftUI

class ViewRouter: ObservableObject {
    
}

As said, an ObservableObject notifies and causes all of its observing views to update themselves when a change happens. But what exactly do we mean with “when a change happens”? As said, the main task of our ViewRouter should be to stay tracked on which Page (meaning which ContentView) should be currently shown – whether it’s on the launch of the app or when the user taps on a specific Button. For this purpose, we declare a variable called currentPage inside our ViewRouter class and assign .page1 to it as its default value.

class ViewRouter: ObservableObject {
    
    var currentPage: Page = .page1
    
}

The views that will observe the ViewRouter, especially the MotherView, should get notified and updated when the Page assigned to the currentPage changes. 

To do this, we use the @Published property wrapper.

@Published var currentPage: Page = .page1

The @Published property wrapper works very similarly to the @State property wrapper. Every time the value assigned to the wrapped property changes, every observing view rerenders. In our case, we want our MotherView to observe the ViewRouter and to navigate to the right Page depending on the currentPage’s updated value.

Updating the MotherView 🔁

To make the MotherView observe the ViewRouter, we need to declare a @StateObject property, which is used for binding views to ObservableObjects.

struct MotherView: View {
    
    @State var currentPage: Page = .page1
    
    @StateObject var viewRouter: ViewRouter

    var body: some View {
        //...
    }
}

When doing this, we also need to provide our MotherView_Previews struct with an instance of the ViewRouter.

struct MotherView_Previews: PreviewProvider {
    static var previews: some View {
        MotherView(viewRouter: ViewRouter())
    }
}

In the NavigatinInSwiftUIApp.swift file, we defined the MotherView as the root view when the app launches. Thus, not only does our preview simulator need to be provided with a ViewRouter instance, but also the actual App hierarchy when the app gets executed on a real device or in the regular simulator.

So, go to the NavigatingInSwiftUIApp file and declare a @StateObject property. Then, pass the initialised @StateObject to the viewRouter of our MotherView.

@main
struct NavigatingInSwiftUIApp: App {
    
    @StateObject var viewRouter = ViewRouter()
    
    var body: some Scene {
        WindowGroup {
            MotherView(viewRouter: viewRouter)
        }
    }
}

Our MotherView router is now able to observe and access the viewRouter‘s OberservableObject. So, let’s show the corresponding ContentView depending on the Page assigned to the viewRouter‘s currentPage property.

var body: some View {
    switch viewRouter.currentPage {
    case .page1:
        ContentViewA()
    case .page2:
        ContentViewB()
    }
}

You can delete the currentPage State of the MotherView, since we won’t need it anymore.

Let’s take a look at the simulator of our MotherView: The MotherView reads the value of the ViewRouter’s currentPage variable and hosts the corresponding ContentView. You can proof this by changing the default value assigned to the ViewRouter’s currentPage property to .page2. Go back to the MotherView preview simulator and see what happens! The @Published property of our ObservableObject told the MotherView to update its body.

Because we want ContentViewA to be the default view, assign .page1 to the currentPage property again.

Great! We accomplished a lot so far! We initialised a ViewRouter instance and bound it to the MotherView by using a @StateObject. Every time the values assigned to the currentPage property of the ViewRouter instance gets updated, the MotherView will rerender its body with eventually showing the correct ContentView!

Bind the ContentViews to the ViewRouter ⛓

Our MotherView is now able to show the correct ContentView depending on the Page assigned to the currentPage property of the ViewRouter. But until now, the user is not able to change this value by tapping on the respective Button of ContentViewA and ContentViewB.

Let’s start with ContentViewA. To let it access the currentPage and manipulate its value we have to bind it to the ViewRouter. So, let’s create an @StateObject again. 

struct ContentViewA: View {
    
    @StateObject var viewRouter: ViewRouter
    
    var body: some View {
        //...
    }
}

We need to update the ContentViewA_Previews struct again.

struct ContentViewA_Previews: PreviewProvider {
    static var previews: some View {
        ContentViewA(viewRouter: ViewRouter())
    }
}

ContentViewA should observe the ViewRouter instance we created inside the NavigatingInSwiftUI struct and passed to the MotherView. So, let’s assign our new @StateObject to this instance when initialising ContentViewA in our MotherView.

switch viewRouter.currentPage {
case .page1:
    ContentViewA(viewRouter: viewRouter)
case .page2:
    ContentViewB()
}

Great! Now we have access to the currentPage property of our viewRouter. Use the Button’s action closure to assign .page2 to it when tapping on the “Next” Button.

Button(action: {
    viewRouter.currentPage = .page2
}) {
    NextButtonContent()
}

Okay, let’s see if that works: Run the app in the regular simulator or start a Live preview of the MotherView and tap on the “Next” button. Great, we successfully navigate to ContentViewB! 

This is what happens when the user taps on the “Next” Button of ContentViewA: ContentViewA changes the Page assigned to the currentPage property of the viewRouter to .page2. Therefore, the viewRouter tells all bound views to rerender their bodies, including the MotherView. The MotherView updates its body and checks the currentPage‘s value. Because it’s .page2 now, the case for showing ContentViewB is met and we eventually navigate to it!

To be able to navigate back to ContentViewA, repeat this implementation process for ContentViewB:

Declare a @StateObject property as a ViewRouter instance…

struct ContentViewB: View {
    
    @StateObject var viewRouter: ViewRouter
    
    var body: some View {
        //...
    }
}

…and update the related previews struct:

struct ContentViewB_Previews: PreviewProvider {
    static var previews: some View {
        ContentViewB(viewRouter: ViewRouter())
    }
}

Assign this viewRouter property to the initial ViewRouter instance passed by the NavigatingInSwiftUIApp struct to the MotherView.

switch viewRouter.currentPage {
case .page1:
    ContentViewA(viewRouter: viewRouter)
case .page2:
    ContentViewB(viewRouter: viewRouter)
}

Then, update the Button’s action parameter for showing the first page again:

Button(action: {
    viewRouter.currentPage = .page1
}) {
    BackButtonContent()
}

We can now navigate independently between our ContentViews!

Conclusion 🎊

We just figured out how to navigate between different views using an @ObservableObject. We created a ViewRouter and bound our MotherView and the ContentViews to it. Then, we achieved to manipulate the ViewRouter’s currentPage property when clicking on the ContentViews Buttons. Due to the @Published property wrapper’s functionality, this causes the MotherView to rebuild its body with eventually hosting the correct ContentView! 

You can download the whole source code here!

But often, there is an alternative, more efficient way to do this: Using an @EnvironmentObject. EnvironmentObjects provide us with more freedom and independence within our app’s view hierarchy. You will see what we mean by that when reading the second part of this tutorial ! We will also talk about adding animated transitions, so make sure you check it out!

13 replies on “How to navigate between views in SwiftUI by using an @ObservableObject”

I downloaded the application from your github and ran the starter application. The next button does not navigate to the next screen. Coming across the same problem in my own application. Any idea why that’s happening?

Hey there! We just checked the repository and everything seems to work fine. Did you make sure you opened the project in the “NavigateInSwiftUIComplete” folder? Also note that navigating only works when running the app in the regular simulator and not in the SwiftUI preview

Stumbled across this same issue. Turns out I misplaced some parentheses in the MotherView. ContentViewA(viewRouter: viewRouter()) instead of ContentViewA(viewRouter: viewRouter). This may not be the cause of your issue, but it may help to check your code for similar issues that don’t cause an error in the editor!

That’s not even near to navigating between views, this is actually swapping between the views. For navigation, you need to use NavigationView, which stacks up the view in a hierarchy. I think you should rename this article.

Hello user832, thanks for your comment. In the first paragraph we make clear that the tutorial is not about navigating within a stack hierarchy using a NavigationView.

Thank you, that is a very good example without navigation. If I don’t use @ObservedObject as a router, I only use button to open another view(there are no data to be transferred), but there is an error ,like Result of ‘anotherView’ initializer is unused, how to initialize anotherView?

code likes: Button(action: {self.viewRouter.currentPage = “page1”}) {BackButtonContent()}

Select the Navigate InSwiftUI Target in the Project Editor, then check the Mac box under the General tab and rebuild.
Make sure tour Mac is showing in the Scheme selector, then Run
You may needSigningCertificate set to Sign to Run Locally under the
Signing & Capabilities tab , and

Great article !! Many Many thanks 🙂 What if, this is to be achieved using NavigationView and passing observable objects through navigationLink?

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount