Reputation: 407
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()
}
}
Upvotes: 4
Views: 7820
Reputation: 2195
SwiftUI
is managing the memory of @State
and @Binding
objects and automatically refreshes any UI of any View
s 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.
Upvotes: 5