The NavigationView
view is a crucial component in SwiftUI that you will frequently use in your app development. By wrapping your views within a NavigationView
, you gain access to several beneficial features.
Let’s start by taking a look at a basic NavigationView
:
NavigationView {
}
Once you have enclosed a view within a NavigationView
, you can easily add a title to the view using the navigationTitle()
modifier:
NavigationView {
Text("Hello")
.navigationTitle("Welcome")
}
However, the primary advantage of the NavigationView
lies in its ability to create navigation links between different views.
To begin, let’s create another view. You can either add it to the same file or place it in a separate file within your project:
struct ThanksView: View {
var body: some View {
Text("Thanks for checking out the app!")
}
}
Next, wrap the “Hello” Text
view within a NavigationLink
view, setting the destination parameter to ThanksView
:
NavigationView {
NavigationLink(destination: ThanksView()) {
Text("Hello")
.navigationTitle("Welcome")
}
}
Now, several things will happen automatically: the text “Hello” becomes tappable and turns blue:
Upon tapping, the ThanksView
will be displayed, along with a link to return to the original view. The text displayed on the top-left button is derived from the navigationTitle
modifier we set:
Here’s the complete code used in the example:
import SwiftUI
struct ThanksView: View {
var body: some View {
Text("Thanks for checking out the app!")
}
}
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: ThanksView()) {
Text("Hello")
.navigationTitle("Welcome")
}
}
}
}
This represents a straightforward and concise way to navigate between views.
Sometimes, before navigating to another view, you may want to perform some action. In this case, you can use a boolean property, such as showThanks
, which can be set to true
when you want the ThanksView
to appear. You can achieve this by connecting it to a button tap event:
struct ContentView: View {
@State private var showThanks = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: ThanksView(), isActive: $showThanks) {}
Button("Hello") {
showThanks = true
}
.navigationTitle("Welcome")
}
}
}
}
Visually, the app remains the same as before. However, now when the user taps the button, you can execute additional actions, such as logging the transition. For example:
Button("Hello") {
showThanks = true
print("Transitioned to ThanksView")
}
Remember that
print()
statements will not be logged in preview mode but will work in the Simulator.
Tags: SwiftUI, NavigationView, SwiftUI NavigationLink, SwiftUI navigationTitle