What causes updateUIView() to be called in this code?

て烟熏妆下的殇ゞ 提交于 2020-05-17 07:53:05

问题


I understand that the change of the @State variable notifies the @Binding that the state has changed but what then causes the updateUIView() method to be called? There is obviously some hidden connection between the @Binding and the call, but how does that work?

//  Experiment_Map_View.swift

import SwiftUI
import MapKit

struct Experiment_Map_View: UIViewRepresentable {
    @Binding var test: Bool

    func updateUIView(_ uiView: MKMapView, context: Context) {
        print("updateUIView")
        print(test)
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    final class Coordinator: NSObject, MKMapViewDelegate {
        var control: Experiment_Map_View

        init(_ control: Experiment_Map_View) {
            print("init -----------------")
            self.control = control
        }

    }

    func makeUIView(context: Context) -> MKMapView {
         print("makeUIView")
        let map = MKMapView()
        map.delegate = context.coordinator
        return map
    }
}

struct MyRootView: View {
    @State var test: Bool = true

    var body: some View {
        ZStack {
            Experiment_Map_View(test: $test)
            VStack {
                Spacer()
                Button("Next") {
                    print("Next")
                    self.test.toggle()
                }
            }
        }
    }

}

struct Experiment_Map_View_Previews: PreviewProvider {
    static var previews: some View {
        MyRootView()
    }
}

回答1:


SwiftUI is managing the memory of @State and @Binding objects and automatically refreshes any UI of any Views that rely on your variable. SwiftUI is closed source so unfortunately we don’t know exactly how this is done yet, but for simplicity it could be thought of as a behind the scenes didSet modifier.



来源:https://stackoverflow.com/questions/57836235/what-causes-updateuiview-to-be-called-in-this-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!