SwiftUI view is not updating to EnvironmentObject change

前端 未结 1 612
感情败类
感情败类 2021-02-06 01:58

I\'m creating a SwiftUI app that includes Firebase to enable logging into an account, extremely simple, just a ui form with password and email fields, then a button to submit. O

相关标签:
1条回答
  • 2021-02-06 02:07

    Try to make use of the @Published property. Try to implement something like this:

    class SessionStore : ObservableObject {
        @Published var session: User
    }
    
    class User: ObservableObject {
        @Published var uid: String
        @Published var email: String?
        @Published var displayName: String?
    
        init(uid: String, displayName: String?, email: String?) {
            self.uid = uid
            self.email = email
            self.displayName = displayName
        }
    
    }
    

    This should update your view when a change was made in the User object, like the email or displayname because they're Published. Hope this will help, gl

    UPDATED:

    Because SwiftUI doesn't support nested Observables yet, you need to notify your main model by yourself.

    See this snippet how to work with a nested ObservableObject inside a ObservableObject:

    class Submodel1: ObservableObject {
      @Published var count = 0
    }
    
    class Submodel2: ObservableObject {
      @Published var count = 0
    }
    
    class Model: ObservableObject {
      @Published var submodel1: Submodel1 = Submodel1()
      @Published var submodel2: Submodel2 = Submodel2()
    
        var anyCancellable: AnyCancellable? = nil
        var anyCancellable2: AnyCancellable? = nil
    
        init() {
    
            anyCancellable = submodel1.objectWillChange.sink { (_) in
                self.objectWillChange.send()
            }
    
            anyCancellable2 = submodel2.objectWillChange.sink { (_) in
                self.objectWillChange.send()
            }
        }
    }
    

    When data inside a submodel changes, the main Model will notify itself. This will result in a update on the view.

    Let me know if this helped you out.. Goodluck!

    0 讨论(0)
提交回复
热议问题