SwiftUI - 如何将视图关闭到根目录,然后立即推送第二个视图?
Posted
技术标签:
【中文标题】SwiftUI - 如何将视图关闭到根目录,然后立即推送第二个视图?【英文标题】:SwiftUI - How can I dismiss a view to root and then push a second view immediately afterwards? 【发布时间】:2021-01-23 09:10:53 【问题描述】:在 SwiftUI 中找不到与此问题相关的任何内容。
我目前有三个视图,RootView、DetailView1 和 DetailView2。 RootView 将具有一个按钮来推送和显示 DetailView1,在 DetailView1 内部将有一个 NavigationLink 将 DetailView1 关闭到 RootView 并推送 DetailView2。
struct DetailView1: View
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View
VStack
NavigationLink(destination: DetailView2())
Text("Tap to dismiss DetailView and show DetailView2")
.onTapGesture
self.presentationMode.wrappedValue.dismiss()
struct DetailView2: View
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View
Button(
"This is DetailView2",
action: self.presentationMode.wrappedValue.dismiss()
)
struct RootView: View
var body: some View
VStack
NavigationLink(destination: DetailView1())
Text("This is root view. Tap to go to DetailView")
struct ContentView: View
var body: some View
NavigationView
RootView()
预期行为: 用户在 DetailView1 中按下 NavigationLink,视图被解除到 RootView 并且 DetailView2 被向上推。
当前行为: 用户在DetailView1中按下NavigationLink,视图被解除到RootView,DetailView2没有被推送。
【问题讨论】:
【参考方案1】:您可以通过传递第二个视图的活动状态来做到这一点。并更改@State 值。类似于 UIKit 中的完成块的概念。
详细视图1
struct DetailView1: View
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@Binding var isActiveDetails2: Bool //<-- Here
var body: some View
VStack
Button("Tap to dismiss DetailView and show DetailView2")
isActiveDetails2 = true //<-- Here
根视图
struct RootView: View
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@State private var isActiveDetails2: Bool = false
var body: some View
VStack
NavigationLink(destination: DetailView1(isActiveDetails2: $isActiveDetails2))
Text("This is root view. Tap to go to DetailView")
NavigationLink(destination: DetailView2(), isActive: $isActiveDetails2) //<-- Here
EmptyView()
【讨论】:
以上是关于SwiftUI - 如何将视图关闭到根目录,然后立即推送第二个视图?的主要内容,如果未能解决你的问题,请参考以下文章
如何将关闭按钮从 swiftui 视图的主结构(由 uihostingviewcontroller 呈现)分离到它自己的结构?
如何在 onReceive 计时器关闭 SwiftUI iOS 中导航另一个视图
SwiftUI - 如何关闭假的模态视图 - 从里面的第二个视图,用关闭按钮?