Go to another view in SwiftUI using NavigationView


In this tutorial, I will go through how to go to another view in SwiftUI using NavigationView.

In SwiftUI, NavigationView is a container that can be used to manage other views in a navigation interface. Using the NavigationView container and NavigationLink() button inside it, we can send the user to another view.

Not only the user can go to another view, but also it allows the user to back from the destination view using the Back button. Yes, NavigationView also will create a Back button in the top right corner.

Before we start writing our code for going to the next view, first create our new view which will be the destination view.

Create a new view by clicking File > New > File and then choose SwiftUI from User Interface and click on Next. In this example, we have given the name MyView to our new view.

Below is given the SwiftUI code for MyView:


import SwiftUI

struct MyView: View {
    var body: some View {
        Text("Text from MYView")
    }
}

Now, let’s see the code in our main view:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        NavigationView {
        
        VStack {
            
            
            Text("Our Main View")
            Spacer()
            
            NavigationLink(destination: MyView()) {
                Text("Send Me").padding().background(Color.green)
                

            }
            
        }
        
        }
        
    }

}

As you can see in our main view, all the content is inside NavigationView. In this view, we have our NavigationLink() button with the text “Send Me”. We set the padding and the color green.

Let’s run our iOS project and you will able to see the screen given below:

SwiftUI iOS View

If you click the “Send Me” button, it will send you to view MyView. You will also be able to see a back button. Clicking the back button will return you to the main content view.

That’s it. we are successfully able to send the user to another SwiftUI view by tapping a button.