How to Use NavigationView in SwiftUI for iOS and iPadOS

The Navigation View in SwiftUI allows you to switch between views in a hierarchical way using the Navigation Bar, large title, and swipe gesture.

In this tutorial. we will learn How to create native navigation for your app using the nav bar, large title, and swipe gesture.

Navigation View Wrapper

  • At the root level of your navigation structure, you should wrap everything inside a Navigation View. 
  • This will automatically create a Navigation Bar. 
  • Please note that you should only do this once and that includes all the child's views.

NavigationView {
    ScrollView {
        RoundedRectangle(cornerRadius: 30)
            .frame(height: 1000)
            .padding()
    }
}

..

Navigation Title 

  • The navigationTitle modifier should be applied to the first wrapper inside the NavigationView. 
  • It should not be applied to the NavigationView itself. In this case, I'm applying to the ScrollView container.

NavigationView {
	ScrollView {
		// ...
	}
	.navigationTitle("Today") 
}

As a bonus, you get a large title by default and when you scroll, the title transitions to the Navigation Bar.

..

Navigation Bar Items

You can add buttons to the left or right of your navigation bar by using the navigationBarItems modifier.

.navigationBarItems(trailing: Image(systemName: "person.crop.circle"))

..

Navigation Link 

  • NavigationLink is what allows you to navigate to another screen. 
  • It will trigger the default slide animation with a Navigation Bar. 
  • Additionally, you can swipe back to the previous screen.

NavigationLink(destination: Text("New View")) {
    RoundedRectangle(cornerRadius: 30)
        .frame(height: 1000)
        .padding()
}

..

Comments