【问题标题】:How to go to another page from a sheet view in SwiftUI?如何从 SwiftUI 中的工作表视图转到另一个页面?
【发布时间】:2020-10-25 13:12:11
【问题描述】:

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

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.")
        }
    }
}

问题是第三个视图也将在该表中。是否可以使第三个视图成为普通页面而不是工作表中的视图?

谢谢!

【问题讨论】:

    标签: ios swift swiftui swiftui-navigationlink


    【解决方案1】:

    NavigationLink 应该在 NavigationView 的同一视图层次结构中才能工作,但 .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
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2021-05-02
      • 2020-03-31
      • 2020-06-21
      • 1970-01-01
      • 2015-12-12
      • 2021-10-15
      • 2021-12-07
      • 1970-01-01
      相关资源
      最近更新 更多