首页 > 解决方案 > SwiftUI 关闭所有活动呈现的视图控件并弹出到根视图控制器

问题描述

我正在尝试关闭所有活动的呈现视图控制器并推送视图控制器,但我遇到了一些问题并且没有得到预期的输出。

ContentView -> Pushed(LoginView) -> Presented(HomeView) -> 预期直接返回 (ContentView),没有任何动画滞后,也没有显示中间动画。它应该直接显示内容视图。

这是我的代码:


import SwiftUI

struct FirstView: View {
    @State var showLoginView = false
    
    var body: some View {
        NavigationView {
            VStack(spacing: 16) {
                Text("FirstView View")
                    .font(.largeTitle)
                    .foregroundColor(.red)
                NavigationLink( destination: SecondView(), isActive: $showLoginView, label: {
                    Text("Show SecondView")
                })
            }
        }
    }
}

struct SecondView: View {
    
    @State var showHomeView = false
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var body: some View {
        VStack(spacing: 16) {
            Text("Second View")
                .font(.largeTitle)
                .foregroundColor(Color(.systemPurple))
            Button(action: { showHomeView = true }, label: {
                Text("Show ThirdView")
                    .padding()
            })
        }
        .sheet(isPresented: $showHomeView, onDismiss: { presentationMode.wrappedValue.dismiss() }) {
            ThirdView()
        }
    }
}

struct ThirdView: View {
    @Environment(\.presentationMode) var presentationMode
    
    @State var showFormView = false
    var body: some View {
        VStack(spacing: 16) {
            Text("Third View")
                .font(.largeTitle)
                .foregroundColor(Color(.systemTeal))
            Button(action: {
                showFormView = true
                presentationMode.wrappedValue.dismiss()
            }, label: {
                Text("Back to FirstView")
                    .padding()
            })
        }
    }
}

标签: swiftui

解决方案


推荐阅读