问题
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