SwiftUI: NavigationLink not working if not in a Li

2020-07-06 02:47发布

问题:

I guess it might be a bug in beta 3 as the NavigationView is all broken. But a view like that:

struct GenreBadge : View {
    @EnvironmentObject var store: Store<AppState>
    let genre: Genre

    var body: some View {
        NavigationLink(destination: MoviesGenreList(genre: genre).environmentObject(store)) {
            RoundedBadge(text: genre.name)
        }
    }
}

is not triggering any push in the navigation stack. The view doens't seems interactive at all. If anyone found a workaround would be good, unless Apple is documenting this behaviour I would consider it broken until beta 4.

回答1:

There seems to be a bug with the navigation link in Xcode version 11.3(11C29) which I have reported to Apple.

Note: This problem only appears in simulator. It works fine on a real device. Thanks to @djr

The below code works as expect the first time you use the navigation link. Unfortunately it becomes unresponsive the second time around.

import SwiftUI

struct ContentView : View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: SomeView()) {
                    Text("Hello!")
                }
            }
        }
    }
}

struct SomeView: View {
    var body: some View {
        Text("Detailed View")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


回答2:

Are you actually inside a NavigationView? The following works. But if I missed your point, maybe you can share a little more code.

import SwiftUI

struct ContentView : View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: SomeView()) {
                    Text("Go!")
                }
            }
        }
    }
}

struct SomeView: View {
    var body: some View {
        Text("Detailed View Here!")
    }
}


回答3:

Try this:-

var body: some View {
        NavigationView {
            NavigationButton(destination: YourView()) {
                Text("Go!")
            }
        }
    }


回答4:

NavigationLink

A button that triggers a navigation presentation when pressed. This is a replacement for pushViewController

NavigationView {
    NavigationLink(destination:
        Text("Detail")
        .navigationBarTitle(Text("Detail"))
    ) {
        Text("Push")
    }.navigationBarTitle(Text("Master"))
}

Or make it more readable by use group destination into it own view DetailView

NavigationView {
    NavigationLink(destination: DetailView()) {
        Text("Push")
    }.navigationBarTitle(Text("Master"))
}


标签: swift swiftui