在@EnvironmentObject 中更改为@Published var 不会立即反映出来 [英] Change to @Published var in @EnvironmentObject not reflected immediately
问题描述
在这种特定情况下,当我尝试更改 @EnvironmentObject
的 @Published var
时,我发现该视图不会立即失效并更新.相反,对变量的更改仅在导航离开模态并返回后才会反映出来.
In this specific case, when I try to change an @EnvironmentObject
's @Published var
, I find that the view is not invalidated and updated immediately. Instead, the change to the variable is only reflected after navigating away from the modal and coming back.
import SwiftUI
final class UserData: NSObject, ObservableObject {
@Published var changeView: Bool = false
}
struct MasterView: View {
@EnvironmentObject var userData: UserData
@State var showModal: Bool = false
var body: some View {
Button(action: { self.showModal.toggle() }) {
Text("Open Modal")
}.sheet(isPresented: $showModal, content: {
Modal(showModal: self.$showModal)
.environmentObject(self.userData)
} )
}
}
struct Modal: View {
@EnvironmentObject var userData: UserData
@Binding var showModal: Bool
var body: some View {
VStack {
if userData.changeView {
Text("The view has changed")
} else {
Button(action: { self.userData.changeView.toggle() }) {
Text("Change View")
}
}
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
MasterView().environmentObject(UserData())
}
}
#endif
这是一个错误还是我做错了什么?
Is this a bug or am I doing something wrong?
如果 changeView
是 Modal 中的 @State var
,则此方法有效.如果它是 MasterView
内的 @State var
和 Modal
内的 @Binding var
,它也可以工作.它只是不适用于此设置.
This works if changeView
is a @State var
inside Modal. It also works if it's a @State var
inside MasterView
with a @Binding var
inside Modal
. It just doesn't work with this setup.
推荐答案
变化
final class UserData: NSObject, ObservableObject {
到
final class UserData: ObservableObject {
确实修复了 Xcode11 Beta6 中的问题.SwiftUI 似乎没有正确处理实现 ObservableObject
的 NSObject
子类(至少它似乎没有调用它的内部 willSet
块).
does fix the issue in Xcode11 Beta6. SwiftUI does seem to not handle NSObject
subclasses implementing ObservableObject
correctly (at least it doesn't not call it's internal willSet
blocks it seems).
这篇关于在@EnvironmentObject 中更改为@Published var 不会立即反映出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!