Programmatic navigation in SwiftUI with NavigationPath and navigationDestination


Printed on: Might 22, 2024

One of many key options that was lacking from SwiftUI when it first shipped was a great way to do programmatic navigation. There have been some methods to deal with this earlier than iOS 16 launched NavigationPath however it wasn’t very satisfying to make use of these APIs they usually may very well be fairly unreliable at occasions. To see an instance, check out this put up I wrote about dealing with deeplinks on iOS 14.

On this put up, I’d wish to revisit programmatic navigation by iOS 16’s NavigationPath API which is a large leap ahead by way of developer expertise and reliability on the identical time.

On this put up we’ll have a look at:

  • Understanding iOS 16’s navigation API
  • Navigating by a NavigationPath

Understanding iOS 16’s navigation API

On iOS 16, Apple launched the NavigationStack view. This can be a view that’s just about analogous to UIKit’s UINavigationController and it permits builders to implement stack-based navigation. That is the sort of navigation that you just’ll truly discover in most apps that will let you navigate into gadgets which might be proven in a listing for instance.

A navigation view in iOS has a stack of views that it holds on to as a hierarchy of how the consumer obtained to the place they presently are. For instance, the foundation view is perhaps a listing, the subsequent view is perhaps a film view and the subsequent one is perhaps a view the place customers can view the solid of a film. Every view would exist on the stack and a consumer can navigate again one degree by swiping from the sting of their display screen.

I’m certain you’re acquainted with the UX of this.

The stack of views that represents the navigation hierarchy wasn’t out there to make use of till iOS 16. The principle distinction between UIKit’s UINavigationController and the way NavigationStack manages its navigation is that in SwiftUI we will truly navigate primarily based on fashions.

Which means that we will map cases of, for instance, a Film mannequin to a MovieView that may current a film to the consumer.

Primarily because of this we will mannequin a navigation hierarchy utilizing mannequin knowledge fairly than views.

Let’s check out an instance of how we will arrange a NavigationStack together with a element web page for a given mannequin kind. We gained’t introduce a NavigationPath simply but. Behind the scenes our NavigationStack will handle its personal path if we don’t present one so we’ll simply depend on that for now.

The code beneath defines a easy listing view with NavigationLink views to allow navigation. Discover that the NavigationLink receives a worth as an alternative of a vacation spot. Additionally, discover how we’re making use of a navigationDestination view modifier to specify a vacation spot view for our mannequin.

struct ContentView: View {
  @State personal var workouts: [Exercise] = Train.pattern

  var physique: some View {
    NavigationStack {
      ExercisesList(workouts: workouts)
        .navigationDestination(for: Train.self, vacation spot: { train in
          ExerciseDetail(train: train)
        })
    }
  }
}

struct ExercisesList: View {
  let workouts: [Exercise]

  var physique: some View {
    Checklist(workouts) { train in
      NavigationLink(worth: train, label: {
        ExerciseListItem(train: train)
      })
    }
    .navigationTitle("My workouts")
  }
}

What’s particularly attention-grabbing right here is the place we apply the navigationDestination view modifier.

I selected so as to add it to my listing. Which means that any NavigationLink inside my listing with an occasion of Train as its worth will use the vacation spot view that I offered as its view. Which means that I can outline my vacation spot views multi function place which implies that I can shortly purpose about which view might be proven for a mannequin.

If I had been to outline a second navigationDestination for a similar mannequin kind on my Checklist, that second vacation spot would overwrite my first. This enables me to override the vacation spot if wanted so that every view can nonetheless explicitly outline its personal “exit views” however it’s not required. That is actually highly effective and permits for very versatile navigation setups.

At this level, we’re capable of push new fashions onto our navigation stack’s navigation path utilizing our navigation hyperlink and we’ve configured a vacation spot view utilizing the navigationDestination view modifier.

Now let’s arrange a navigation path so we will begin performing some programmatic navigation, lets?

Navigating with a NavigationPath

A NavigationStack could be arrange with a NavigationPath object which can will let you acquire management over the stack’s navigation hierarchy.

The best technique to arrange a NavigationPath is as follows:

struct ContentView: View {
  @State personal var workouts: [Exercise] = Train.pattern
  @State personal var path = NavigationPath()

  var physique: some View {
    NavigationStack(path: $path) {
      ExercisesList(workouts: workouts)
        .navigationDestination(for: Train.self, vacation spot: { train in
          ExerciseDetail(train: train)
        })
    }
  }
}

With this code, we’re not but doing something to realize management of our navigation path. We’re simply making an occasion of NavigationPath and we go a binding to NavigationStack. Any longer, every time we navigate to a brand new view, the mannequin that’s used as a worth might be added to the trail we created.

Primarily, when a consumer faucets on a NavigationLink, we take the mannequin occasion that was handed as a worth and it’s added to the navigation path routinely.

We will go any Hashable mannequin as the worth for a navigation vacation spot and we will additionally combine fashions. So we might go cases of Train, Int, String, and extra to the identical navigation path.

The truth is, you usually don’t fear about which mannequin varieties you go. You simply go the mannequin that you should draw your vacation spot view and also you let the system deal with all the things else.

Let’s check out how we will substitute our NavigationLink with a Button so we will manually append our mannequin to the NavigationPath that we’ve created earlier than.

We will create a binding to the NavigationPath and we go it to the ExercisesList, permitting it to append new gadgets to the trail which can enable the NavigationStack to navigate to the vacation spot for our mannequin:

struct ContentView: View {
  @State personal var workouts: [Exercise] = Train.pattern
  @State personal var path = NavigationPath()

  var physique: some View {
    NavigationStack(path: $path) {
      // 1
      ExercisesList(workouts: workouts, path: $path)
        .navigationDestination(for: Train.self, vacation spot: { train in
          ExerciseDetail(train: train)
        })
    }
  }
}

struct ExercisesList: View {
  let workouts: [Exercise]
  // 2
  @Binding var path: NavigationPath

  var physique: some View {
    Checklist(workouts) { train in
      Button(motion: {
        // 3
        path.append(train)
      }, label: {
        ExerciseListItem(train: train)
      })
    }
    .navigationTitle("My workouts")
  }
}

Earlier than I clarify the code, let me say that I don’t assume this can be a good thought. The code was higher with NavigationLink. That stated, the purpose of this instance is to demo placing gadgets in a NavigationPath programmatically which we will do from a button handler.

First, we go a binding to our navigation path to the listing view. Which means that now our NavigationStack and ExercisesList each have entry to the very same NavigationPath occasion.

The ExercisesList was up to date to take a binding to a NavigationPath, and we’ve swapped the NavigationLink out in favor of a Button. Within the button handler, I name append with the Train mannequin for the button on path. This can add the mannequin to the trail which can trigger SwiftUI to navigate to the vacation spot view for that mannequin.

That is actually cool!

Along with appending components to the trail, we will truly take away gadgets from the trail too by calling take away on it.

We will even get the variety of gadgets on the trail to implement a “pop to root” type perform:

func popToRoot() {
  path.removeLast(path.rely)
}

This perform will take away all components from the navigation stack’s path, solely leaving its root to be displayed.

The API for NavigationPath is admittedly versatile. You possibly can even add a number of views in a single go, ensuing within the final added view turning into the highest every person others being a part of the stack so the consumer sees them once they navigate again.

In Abstract

With NavigationPath we’ve gained a great deal of energy by way of having the ability to navigate programmatically. By leveraging model-based navigation we will signify a navigation stack’s hierarchy as knowledge fairly than views, and we’re capable of go our NavigationPath round by bindings in an effort to enable views to append new fashions to the trail.

Dealing with deeplinks and restoring navigation stacks with NavigationPath is hundreds higher than it was pre iOS 16 and I’m certain that Apple will hold enhancing NavigationPath over time to make managing navigation by code higher and higher.

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox