5️⃣Navigation

Fall 2023 | Vin Bui

Of course our app won’t have just a single screen — we typically have multiple screens that we want to navigate to and from. In SwiftUI, navigation between views is very simple and similar to that of UIKit.

Creating a Navigation Stack

For iOS 16 and later, we use a NavigationStack which is a view that displays a root view and enables us to present additional views over the root view. This is similar to a UINavigationController in UIKit.

NavigationStack {
    // Place views here
}

If we are using iOS 15 or earlier, we can also use a NavigationView which serves the same purpose.

To modify the navigation, we can use modifiers. However, the modifier must be placed in the view nested inside of the NavigationStack, not on the NavigationStack itself.

For example, if we wanted to add a title to the navigation bar, we can use the .navigationTitle modifier. Note that we are using the modifier on the Text view which is inside of the NavigationStack.

NavigationStack {
    Text("AppDev")
        .navigationTitle("Some Title Here")
}

Pushing a View

To push a view, we use a NavigationLink, which is a view that controls a navigation presentation. This is similar to pushing a ViewController in UIKit. There are many different ways to use this; however, the preferred and conventional way to use it is with the trailing closure syntax:

NavigationStack {
    NavigationLink {
        // View that is being pushed (the destination)
    } label: {
        // View that is being tapped on (such as a Text)
    }
}

Last updated