我有以下代码:
import SwiftUI
struct RootView: View {
@ObservedObject var authentication: AuthenticationModel
var body: some View {
ZStack {
if self.authentication.loading {
Text("Loading")
} else if self.authentication.userId == nil {
SignInView()
} else {
ContentView()
}
}
}
}
但是,@ObservedObject
的更改似乎不会触发切换到其他视图。我可以通过渲染“修复”此问题
var body: some View {
VStack {
Text("\(self.authentication.loading ? "true" : "false") \(self.authentication.userId ?? "0")")
}.font(.largeTitle)
ZStack {
if self.authentication.loading {
Text("Loading")
} else if self.authentication.userId == nil {
SignInView()
} else {
ContentView()
}
}
}
突然开始工作。如果监视的属性仅在条件条件中使用,为什么@ObservedObject
似乎没有触发重新渲染?
AuthenticationModel
的代码是:
import SwiftUI
import Combine
import Firebase
import FirebaseAuth
class AuthenticationModel: ObservableObject {
@Published var userId: String?
@Published var loading = true
init() {
// TODO: Properly clean up this handle.
Auth.auth().addStateDidChangeListener { [unowned self] (auth, user) in
self.userId = user?.uid
self.loading = false
}
}
}
答案 0 :(得分:0)
我认为问题可能在于您没有创建AuthenticationModel实例。 您可以在RootView中尝试以下方法吗?:
@ObservedObject var authentication = AuthenticationModel()