SwiftUI 从模态 sheet 过渡到带有导航 Link 的常规视图

SwiftUI transition from modal sheet to regular view with Navigation Link

我正在使用 SwiftUI,我有一个起始页。当用户按下此页面上的按钮时,会弹出模态 sheet。

在模态 sheet 旁边,我有一些这样的代码:

  NavigationLink(destination: NextView(), tag: 2, selection: $tag) {
            EmptyView()
    }

我的模态 sheet 视图包裹在导航视图中。

当标签的值变为 2 时,视图确实转到 NextView(),但它也显示为用户可以从中向下滑动的模态 sheet,我不希望这样.

我想从模式 sheet 转换到常规视图。

这可能吗?我尝试过隐藏导航栏等,但似乎没有什么不同。

如有任何帮助,我们将不胜感激。

您可以通过创建 environmentObject 并将 navigationLink 目标值绑定到 environmentObject 的值然后更改 environmentObject 中的值来完成此操作模态视图。

这是解释我的意思的代码

import SwiftUI

class NavigationManager: ObservableObject{
    @Published private(set) var dest: AnyView? = nil
    @Published var isActive: Bool = false

    func move(to: AnyView) {
        self.dest = to
        self.isActive = true
    }
}

struct Whosebug6: View {
    @State var showModal: Bool = false
    @EnvironmentObject var navigationManager: NavigationManager
    var body: some View {
        NavigationView {
            ZStack {
                NavigationLink(destination: self.navigationManager.dest, isActive: self.$navigationManager.isActive) {
                    EmptyView()
                }

                Button(action: {
                    self.showModal.toggle()
                }) {
                    Text("Show Modal")
                }
            }
        }
            .sheet(isPresented: self.$showModal) {
                secondView(isPresented: self.$showModal).environmentObject(self.navigationManager)
            }
    }
}

struct Whosebug6_Previews: PreviewProvider {
    static var previews: some View {
        Whosebug6().environmentObject(NavigationManager())
    }
}


struct secondView: View {
    @EnvironmentObject var navigationManager: NavigationManager
    @Binding var isPresented: Bool
    @State var dest: AnyView? = nil

    var body: some View {
        VStack {
            Text("Modal view")
            Button(action: {
                self.isPresented = false
                self.dest = AnyView(thirdView())
            }) {
                Text("Press me to navigate")
            }
        }
        .onDisappear {
            // This code can run any where but I placed it in `.onDisappear` so you can see the animation
            if let dest = self.dest {
                self.navigationManager.move(to: dest)
            }
        }
    }
}

struct thirdView: View {
    var body: some View {
        Text("3rd")
            .navigationBarTitle(Text("3rd View"))
    }
}

希望这对您有所帮助,如果您对此代码有任何疑问,请告诉我。