ios - 无法在 SwiftUI 中关闭模式
问题描述
我在关闭 SwiftUI 中的一些模态视图时遇到了问题,并制作了以下示例来说明问题。
下面我们有 4 个视图。这个想法是 App 文件将有一个开关,并根据该开关的 viewForDisplay 属性决定显示哪个视图。
最初,我们显示模态呈现 SecondView 的 FirstView,然后模态呈现 ThirdView。当 ThirdView 将 viewForDisplay 设置为 .fourthView 时,我希望 FirstView/SecondView/ThirdView 堆栈中的所有视图都消失,只看到 FourthView。但是它显示的是 SecondView。
enum ViewForDisplay {
case firstView
case fourthView
}
class ViewModel: ObservableObject {
@Published var viewForDisplay: ViewForDisplay = .firstView
}
@main
struct ModalDismissApp: App {
@ObservedObject var viewModel = ViewModel()
var body: some Scene {
WindowGroup {
switch viewModel.viewForDisplay {
case .firstView:
FirstView(viewModel: viewModel)
case .fourthView:
FourthView()
}
}
}
}
struct FirstView: View {
@State var isPresented: Bool = false
@ObservedObject var viewModel: ViewModel
init(viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
VStack {
Text("First View")
Button(action: {
isPresented = true
}, label: {
Text("Present Second View Modally")
})
}
.fullScreenCover(isPresented: $isPresented, content: {
SecondView(viewModel: viewModel)
})
}
}
struct SecondView: View {
@State var isPresented: Bool = false
@ObservedObject var viewModel: ViewModel
init(viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
VStack {
Text("Second View")
Button(action: {
isPresented = true
}, label: {
Text("Present Third View Modally")
})
}
.fullScreenCover(isPresented: $isPresented, content: {
ThirdView(viewModel: viewModel)
})
}
}
struct ThirdView: View {
@ObservedObject var viewModel: ViewModel
init(viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
VStack {
Text("Third View")
Button(action: {
viewModel.viewForDisplay = .fourthView
}, label: {
Text("Dismiss Modals and go to Fourth View")
})
}
}
}
struct FourthView: View {
var body: some View {
Text("Fourth View")
}
}
这仅在应用两个级别的模态时才会发生。例如,如果我将 viewForDisplay 从 SecondView 设置为 .fourthView 一切正常。但是由于某种原因,当我有多个模态时,它就不起作用了。
我可以通过关闭 ThirdView 然后设置 .viewForDisplay 属性来解决这个问题,但这给了我一个不受欢迎的动画。我只想直接转到我的FourthView,不知道为什么使用多个模态这是一个问题。
解决方案
您首先需要关闭所有显示的控制器,然后切换到第四个视图。
这是简单可行的解决方案。
在第三个视图中,在切换到第四个视图之前,只需关闭所有视图。
struct ThirdView: View {
@ObservedObject var viewModel: ViewModel
init(viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
VStack {
Text("Third View")
Button(action: {
UIApplication.shared.windows.first?.rootViewController?.dismiss(animated: true, completion: {
}) //<-- Dismisss all view
viewModel.viewForDisplay = .fourthView
}, label: {
Text("Dismiss Modals and go to Fourth View")
})
}
}
}
推荐阅读
- vb.net - 使用该文件后尝试删除文件,使用Visual Basic
- angular - 如何通过传递下拉值的 id 自动选择下拉值?
- javascript - 为什么我有时不需要使用'get'而其他时候需要使用'get'进行过滤?
- c++ - 无法将 Arduino NANO 33 IOT 连接到 NEO 6M GPS 模块
- devexpress-mvc - 在网格视图 dev express 中多选 bobox
- laravel - Discord API(将角色授予公会成员)返回 405 错误
- python - 添加滚动条以更新 tkinter python 中的标签?
- cassandra - 如何在 Windows 10 中判断 Java 8 的 Cassandra 3 位置
- javascript - 选择下拉菜单时清除状态
- nms - 使用 NMS 时出现“无法加载模块”错误