简体   繁体   中英

Programmatically push a NavigationLink in iOS16

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?

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

演示

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM