4

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()
    }
}
e987
  • 377
  • 5
  • 10

1 Answers1

3

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.

Charles Maria
  • 2,165
  • 15
  • 15
  • Thank you, I figured out that much. I was hoping someone knew how this is really accomplished "behind the scenes". – e987 Sep 08 '19 at 13:05
  • That’s proprietary Apple knowledge at the moment. The correct answer is that the answer is not yet public because the source code is not yet public. – Charles Maria Sep 08 '19 at 13:09
  • @LotteTortorella do you know the answer to my question here: https://stackoverflow.com/questions/59430099/pencilkit-in-swiftui – simibac Dec 20 '19 at 18:59