【发布时间】:2023-02-04 03:18:56
【问题描述】:
当使用 ObservableObject 中的变量关闭 fullScreenCover 时(用 1.- 注释的行),它显示“不允许从视图更新中发布更改,这将导致未定义的行为。”消息,但使用 @State 变量(用 2.- 注释的行)不显示警告。我不懂为什么。
这是代码:
import SwiftUI
final class DismissWarningVM: ObservableObject {
@Published var showAnotherView = false
}
struct DismissWarningView: View {
@StateObject private var dismissWarningVM = DismissWarningVM()
@State private var showAnotherView = false
var body: some View {
VStack {
HStack {
Spacer()
Button {
// 1.- This line provokes the warning
dismissWarningVM.showAnotherView = true
// 2.- This line DO NOT provokes the warning
//showAnotherView = true
} label: {
Text("Show")
}
}
.padding(.trailing, 20)
Spacer()
Text("Main view")
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.white)
// 1.- This line provokes the warning
.fullScreenCover(isPresented: $dismissWarningVM.showAnotherView) {
// 2.- This line DO NOT provokes the warning
//.fullScreenCover(isPresented: $showAnotherView) {
AnotherView()
}
}
}
struct AnotherView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack(spacing: 30) {
Text("Another view")
Button {
dismiss()
} label: {
Text("Dismiss")
.foregroundColor(.red)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
}
}
struct DismissWarningView_Previews: PreviewProvider {
static var previews: some View {
DismissWarningView()
}
}
【问题讨论】:
标签: swiftui dismiss observableobject