如何从 SwiftUI 中的 sheet 视图转到另一个页面?

How to go to another page from a sheet view in SwiftUI?

我正在尝试从 sheet 视图转到另一个页面。这是第一个视图的代码:

struct FirstView: View {
    @State fileprivate var isShowingSheet: Bool = false

    var body: some View {
        Button(action: {
            isShowingSheet = true
        }) {
            Text("Show the sheet")
        }
        .sheet(isPresented: $isShowingSheet, content: {
            SecondView()
        })
    }
}

这是第二个视图的代码:

struct SecondView: View {
    var body: some View {
        NavigationLink(destination: ThirdView()) {
            Text("Show the third view.")
        }
    }
}

问题是第三个视图也会在 sheet 中。是否可以将第三个视图设为普通页面而不是 sheet 中的视图?

谢谢!

NavigationLink 应该在 NavigationView 的相同视图层次结构中才能工作,但是 .sheet 引入了另一个不同的视图层次结构,因此解决方案是保留(隐藏)导航 link 在上一个视图中,但从 sheet.

中的视图以编程方式激活它

这是一个演示(使用 Xcode 12 / iOS 14 测试)

struct FirstView: View {
    @State fileprivate var isShowingSheet: Bool = false
    @State private var showThirdView = false

    var body: some View {
        Button(action: {
            isShowingSheet = true
        }) {
            Text("Show the sheet")
        }
        .sheet(isPresented: $isShowingSheet, content: {
            SecondView(showNext: $showThirdView)
        })
        .background(
              NavigationLink(destination: ThirdView(), isActive: $showThirdView) {
                    EmptyView()
              }
        )
    }
}

struct SecondView: View {
    @Environment(\.presentationMode) var presentationMode
    @Binding var showNext: Bool

    var body: some View {
        Button("Show the third view.") {
            self.presentationMode.wrappedValue.dismiss()
            DispatchQueue.main.async {
                self.showNext = true
            }
        }
    }
}