How to use BindableObjects (EnviromentObject)?

前端 未结 2 1169
礼貌的吻别
礼貌的吻别 2021-01-24 03:26

Im using the new SwiftUI. I have a UserUpdate class which is a Bindable Object and I want to modify these variables and automatically Update the UI.

相关标签:
2条回答
  • 2021-01-24 03:33

    If I'm not wrong, you should inject the UserUpdate instance in your ContentView, probably in the SceneDelegate, using ContentView().environmentObject(UserUpdate()).

    In that case, you have 2 different instance of the UserUpdate class, the first one created in the SceneDelegate, and the second created in the TestBind class.

    The problem is that you have one instance that is bond to view (and will trigger view reload on update), and the one that you actually modify (in TestBind class) which is totally unrelated to the view.

    You should find a way to use the same instance in the view and in the TestBind class (for example by using ContentView().environmentObject(TestBind.instance.userUpdate)

    0 讨论(0)
  • 2021-01-24 03:36

    I found out that I had to call the method from my UI to get it working so its on the same stream.

    For example by this:

    struct ContentView : View {
    @EnvironmentObject var networkManager: NetworkManager
    
    var body: some View {
        VStack {
            Button(action: {
                self.networkManager.getAllCourses()
            }, label: {
                Text("Get All Courses")
            })
    
            List(networkManager.courses.identified(by: \.name)) {
                Text($0.name)
            }
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题