SwiftUI NavigationView and NavigationLink

Tech Savvy Scribe
2 min readMay 13, 2023

--

Photo by Mohammad Rahmani on Unsplash

In SwiftUI, NavigationView and NavigationLink are fundamental elements used to manage and navigate between views. This tutorial will explore these elements in detail.

“The only impossible journey is the one you never begin.” — Tony Robbins

When it comes to coding, the quote above is quite relevant. Every line of code you write is a step toward your goal.

NavigationView

In SwiftUI, NavigationView is a container view that can host a stack of views, which allows you to navigate between different views.

Here is a simple example:

struct ContentView: View {
var body: some View {
NavigationView {
Text("Hello, World!")
.navigationBarTitle("Home")
}
}
}

In this example, NavigationView hosts a single Text view, and we set the navigation bar title to "Home".

NavigationLink

NavigationLink is a view that provides a button, which, when tapped, will navigate to another view.

Here is a simple example of NavigationLink:

struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: SecondView()) {
Text("Go to Second View")
}
.navigationBarTitle("First View")
}
}
}

struct SecondView: View {
var body: some View {
Text("Welcome to the Second View!")
}
}

In this code, tapping the “Go to Second View” button navigates to SecondView.

Combining NavigationView and NavigationLink

Let’s look at a more advanced example that combines NavigationView and NavigationLink to create a list of items that can navigate to detail views.

struct ContentView: View {
var body: some View {
NavigationView {
List {
ForEach(1...10, id: \.self) { index in
NavigationLink(destination: DetailView(index: index)) {
Text("Item \(index)")
}
}
}
.navigationBarTitle("Items")
}
}
}

struct DetailView: View {
let index: Int

var body: some View {
Text("Detail of Item \(index)")
.navigationBarTitle("Detail", displayMode: .inline)
}
}

In this example, we have a List inside the NavigationView. Each row in the list is a NavigationLink that navigates to a DetailView for the selected item.

Conclusion

SwiftUI’s NavigationView and NavigationLink provide a straightforward way to manage navigation in your apps. With these tools, you can easily create complex navigation hierarchies with minimal code.

If you enjoyed the article and would like to show your support, be sure to:

👏 Applaud for the story (50 claps) to help this article get featured

👉 Follow me on Medium

Check out more content on my Medium profile

--

--

Tech Savvy Scribe

Tech enthusiast exploring software, AI, crypto & personal finance. Unraveling the digital world, one byte at a time. Follow for cutting-edge insights!