SwiftUI: NavigationLink pops immediately if used within ForEach

心已入冬 提交于 2019-12-11 11:00:20

问题


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()
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/58302913/swiftui-navigationlink-pops-immediately-if-used-within-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!