SwiftUI: Exploring the NavigationView View
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
:
1 | NavigationView { |
Once you have enclosed a view within a NavigationView
, you can easily add a title to the view using the navigationTitle()
modifier:
1 | NavigationView { |
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:
1 | struct ThanksView: View { |
Next, wrap the “Hello” Text
view within a NavigationLink
view, setting the destination parameter to ThanksView
:
1 | NavigationView { |
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:
1 | import SwiftUI |
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:
1 | struct ContentView: View { |
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:
1 | Button("Hello") { |
Remember that
print()
statements will not be logged in preview mode but will work in the Simulator.
Tags: SwiftUI, NavigationView, SwiftUI NavigationLink, SwiftUI navigationTitle