SwiftUI 导航。视图在被推送后立即弹出。怎么修?

SwiftUI Navigation. View pops immediately after being pushed. How to fix?

我发现了一个奇怪的错误。瞬间视图在被推后立即开始弹出。我一直在逐段评论代码,直到将其简化为最小的可重现示例。

代码如下:

struct Destination : View {
    private let some: NSArray

    init(some: NSArray) {
        self.some = some
    }

    var body: some View {
        Text("e")
    }
}

struct RecordingsView : View {
    var body: some View {
        GeometryReader { geom in
            // Fill safe area with colors
            VStack {
                Spacer().frame(maxWidth: .infinity, maxHeight: geom.safeAreaInsets.top).background(Color.red)
                Spacer().frame(maxWidth: .infinity).background(Color.white)
            }.edgesIgnoringSafeArea(.bottom).edgesIgnoringSafeArea(.top)

            // Main content
            VStack(spacing: 0) {
                NavigationLink(
                        destination: Destination(some: NSArray(array: [34, 53, 45, 34566])).navigationBarHidden(true)
                ) {
                    Text("WhitePlusButton")
                }.padding(.trailing, 18)

                LazyVStack(spacing: 0) {
                    ForEach(0..<1) { index in
                        NavigationLink(
                                destination: Destination(some: NSArray(array: [34, 53, 45])).navigationBarHidden(true)
                        ) {
                            Text("aaaaa")
                        }
                    }
                }
            }
        }
    }
}

@main
struct VocalTrainerApp: App {
    var body: some Scene {
        WindowGroup {
            NavigationView {
                RecordingsView().navigationBarHidden(true)
            }
        }
    }
}

但是,如果我将 NSArray 替换为 Int 或注释 Spacer().frame(maxWidth: .infinity, maxHeight: geom.safeAreaInsets.top).background(Colors.tone2) 行,则不会重现错误。

如果恰好有两个导航链接,您可能会 运行 出现视图立即弹出的错误。尝试插入带有 EmptyView 的 NavigationLink,如图所示作为临时创可贴。

        NavigationLink(destination: EmptyView()) {
            EmptyView()
        }

您可以在此处找到更多信息: https://forums.swift.org/t/14-5-beta3-navigationlink-unexpected-pop/45279