【发布时间】:2021-03-27 00:25:58
【问题描述】:
我在关闭 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,但不确定为什么使用多个模式会出现问题。
【问题讨论】: