【问题标题】:SwiftUI Navigation. View pops immediately after being pushed. How to fix?SwiftUI 导航。推送后立即弹出视图。怎么修?
【发布时间】:2021-09-08 08:15:28
【问题描述】:

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

代码如下:

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) 行,则不会重现该错误。

【问题讨论】:

    标签: ios swift swiftui swiftui-navigationview


    【解决方案1】:

    如果正好有两个导航链接,您可能会遇到视图立即弹出的错误。尝试插入带有 EmptyViews 的 NavigationLink,如临时创可贴所示。

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

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

    【讨论】:

    • 我爱你。谢谢你。你拯救了我的一天。
    猜你喜欢
    • 2022-01-01
    • 2014-10-03
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2020-04-27
    • 2020-09-28
    相关资源
    最近更新 更多