Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - SwiftUI: NavigationLink pops immediately if used within ForEach

I'm using a NavigationLink inside of a ForEach in a List to build a basic list of buttons each leading to a separate detail screen.

When I tap on any of the list cells, it transitions to the detail view of that cell but then immediately pops back to the main menu screen.

Not using the ForEach helps to avoid this behavior, but not desired.

Here is the relevant code:

struct MainMenuView: View {

    ...

    private let menuItems: [MainMenuItem] = [
        MainMenuItem(type: .type1),
        MainMenuItem(type: .type2),
        MainMenuItem(type: .typeN),
    ]

    var body: some View {
        List {
            ForEach(menuItems) { item in
                NavigationLink(destination: self.destination(item.destination)) {
                    MainMenuCell(menuItem: item)
                }
            }
        }
    }

    // Constructs destination views for the navigation link
    private func destination(_ destination: ScreenDestination) -> AnyView {
        switch destination {
        case .type1:
            return factory.makeType1Screen()
        case .type2:
            return factory.makeType2Screen()
        case .typeN:
            return factory.makeTypeNScreen()
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a @State, @Binding or @ObservedObject in MainMenuView, the body itself is regenerated (menuItems get computed again) which causes the NavigationLink to invalidate (actually the id change does that). So you must not modify the menuItems arrays id-s from the detail view.

If they are generated every time consider setting a constant id or store in a non modifying part, like in a viewmodel.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...