SwiftUI:如果在ForEach中使用,NavigationLink将立即弹出 [英] SwiftUI: NavigationLink pops immediately if used within ForEach

查看:229
本文介绍了SwiftUI:如果在ForEach中使用,NavigationLink将立即弹出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用列表中ForEach内部的NavigationLink来构建按钮的基本列表,每个按钮都导致一个单独的详细信息屏幕.

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.

不使用ForEach可以避免这种现象,但这不是所希望的.

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

以下是相关代码:

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

推荐答案

如果在MainMenuView中具有@State@Binding@ObservedObject,则将重新生成主体本身(再次计算menuItems)这会导致NavigationLink无效(实际上,id更改会导致此无效).因此,您不得从详细信息视图中修改menuItems数组id -s.

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.

如果它们是每次生成的,请考虑设置一个常量id或将其存储在非修改部分中,例如在viewmodel中.

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

这篇关于SwiftUI:如果在ForEach中使用,NavigationLink将立即弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆