SwiftUI NavigationTitle on NavigationLink destination

Viewed 647

How do I add a navigation-like title to the destination of a NavigationLink?

Note that the code is not mine; it comes from Hacking With Swift's Website.

Screenshot of the main navigation view

enter image description here enter image description here

How do I add a title similar to the title in the first screenshot to the destination link in the second screenshot? preferably this title would be horizontally adjacent from the back button.

Code:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack(spacing: 30) {
                Text("You're going to flip a coin – do you want to choose heads or tails?")

                NavigationLink(destination: ResultView(choice: "Heads")) {
                    Text("Choose Heads")
                }

                NavigationLink(destination: ResultView(choice: "Tails")) {
                    Text("Choose Tails")
                }
            }
            .navigationTitle("Navigation")
        }
    }
}

struct ResultView: View {
    var choice: String

    var body: some View {
        Text("You chose \(choice)")
    }
}
1 Answers

Just attach it to the Text (or any topmost view inside body).

struct ResultView: View {
    var choice: String

    var body: some View {
        Text("You chose \(choice)")
            .navigationTitle("Your Title Here")
            .navigationBarTitleDisplayMode(.inline) /// make it horizontally adjacent
    }
}

Result:

"Your Title Here" is centered

Related