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

查看:30
本文介绍了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()
        }
    }

推荐答案

如果您有 @State@Binding@ObservedObjectMainMenuView 中,主体本身被重新生成(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 或存储在非修改部分,如在视图模型中.

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天全站免登陆