Home > other >  Programmatically push a NavigationLink in iOS16
Programmatically push a NavigationLink in iOS16

Time:06-12

In the previous iOS versions, I programmatically pushed a NavigationLink with

NavigationLink(isActive: $searched, destination: { SearchView(originalSearchPhrase: $searchedPhrase) }, label: {})

and toggling the isActive variable when I wanted it to be pushed. However, in iOS16, all of the NavigationLinks with isActive are deprecated. Is there still a way to push NavigationLinks programmatically?

CodePudding user response:

We just need to push corresponding link value into NavigationStack path.

demo

Here is main part. Tested with Xcode 14 / iOS 16

    enum Dest: Hashable {
        case search, details
    }

  @State private var path: [Dest] = []

  var body: some View {
     NavigationStack(path: $path) {
        Button("Go search") { path.append(.search) }  // << here !!
        Divider()
        NavigationLink(value: Dest.search) {
            Text("Search")
        }
        .navigationDestination(for: Dest.self) {
            switch $0 {
            case .search:
                Text("Search Destination Here")

Complete code on GitHub

  • Related