Swift and SwiftUI tutorials for Swift Developers

How to use NavigationLink in SwiftUI

Like list views, navigation views are UI components that are frequently used in iOS apps. They provide a browsing interface for presenting hierarchical content. Take a look at the pre-installed Photos app, YouTube, and Contacts. All of them use navigation views to display content in a hierarchical manner. Typically, you combine a navigation view with a stack of list views to create a sophisticated interface for your apps.

In iOS, you use NavigationStack to create a navigation view.

A navigation interface is used to allow users to navigate to a detailed view, where they can see the details of a selected item.

To navigate between screens, you will need to use the NavigationLink component. This component is equivalent to using the pushViewController or popViewController methods of UINavigationController in UIKit.

NavigationLink is a button that when pressed navigates you to the specified destination. This destination is a new view.

NavigationLink is a view that provides a button that, when tapped, will navigate to another view.

SwiftUI provides a special button called NavigationLink, which can detect user taps and trigger the navigation presentation. The basic usage of NavigationLink is as follows:

NavigationLink(destination: DetailView()) {

  Text("Press me for details")

}

You have to specify the destination view in the destination parameter and customize its appearance in the closure.

This is another example of NavigationLink

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: SecondView()) {
                Text("Go to Second View")
            }
            .navigationBarTitle("First View")
        }
    }
}

struct SecondView: View {
    var body: some View {
        Text("Welcome to the Second View!")
    }
}

In this code, tapping the “Go to Second View” button navigates to SecondView.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

How to change the back button image and color in SwiftUI

Next Article

Customizing the Navigation Bar in SwiftUI

Related Posts