@ObservedObject如果有条件则不会触发重绘

时间:2020-10-24 23:10:12

标签: swift swiftui

我有以下代码:

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
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题可能在于您没有创建AuthenticationModel实例。 您可以在RootView中尝试以下方法吗?:

@ObservedObject var authentication = AuthenticationModel()