How to update a SwiftUI view state from outside (UIViewController for example)

前端 未结 2 2047
既然无缘
既然无缘 2021-01-03 22:39

I have a SwiftUI view:

struct CatView : View {

    @State var eyesOpened: Bool = false

    var body: some View {         


        
2条回答
  •  天命终不由人
    2021-01-03 22:47

    @State is the wrong thing to use here. You'll need to use @ObservedObject.

    @State: Used for when changes occur locally to your SwiftUI view - ie you change eyesOpened from a toggle or a button etc from within the SwiftUI view it self.

    @ObservedObject: Binds your SwiftUI view to an external data source - ie an incoming notification or a change in your database, something external to your SwiftUI view.

    I would highly recommend you watch the following WWDC video - Data Flow Through SwiftUI

提交回复
热议问题