NavigationView is probably onte of the most commonly used SwiftUI widget, and is used by almost all SwiftUI apps.
SwiftUI Widget: NavigationView
Like UINavigtionViewController in UIkit, NavigationView and NavigationLink provide the function to allow user push and pop screen with ease, presenting information in a clear, hierarchical way for users.
In this article, we will demostrate the basic functions of NavigationView. we will build three SwiftUI screen to explain the NavigationView and NavigationLink.
How to navigate from one view to another view
Let’s look at a code snippet
First, in ContentView.swift
1 | struct ContentView: View { |
Second, in SecondView.swift (You should new a SwiftUI file in XCode)
1 | struct SecondView: View { |
Now, after running the SwiftUI app, you will see the first screen (ContentView), click the “Second View”, the screen will be tranfer to SecondView, you should see a title: ‘Second’ at the top left corner and the text “Second View” in the center of screen.
Is it the same when using UINavigtionViewController of UIKit?
Now, we can navigate into third view. Create a new SwiftUI view again.
thirdview:
1 | struct ThirdView: View { |
And change the code of the SecondView
1 | struct SecondView: View { |
Yes, we add a NavigationLink in this SwiftUI view. Now you can push the “Third View” to navigate the third view.
How to pass the parameter to the next SwiftUI view
In SwiftUI, passing the parameters to the next SwiftUi view is very easy.
Consider: we pass a parameter from Second View to Third View. First, let’s define a variable to receive the parameters in Third View. Like this:
1 | struct ThirdView: View { |
Then, let’s pass the value from the second view.
1 | struct SecondView: View { |
So easy?
How to add button to NavigationBar
Can I add the button to navigationBar? Yes, you can. Like UINavigtionViewController, but more easy.
Let’s add two buttons to navigationbar of the ThirdView. Change the code of ThirdView as below:
1 | struct ThirdView: View { |
If you run the SwiftUI app, you can see two buttons at top right corner of ThirdView. But, when you push the button, no action is executed. Because we have writen any code for the action in the button event.
Now, let’s add some action:
1 | struct ThirdView: View { |
About more detail of NavigationView widget, you can see the Official Documentation