是什么导致在此代码中调用updateUIView()?

时间:2019-09-07 18:01:13

标签: swiftui combine

我知道@State变量的更改会通知@Binding状态已更改,但是什么导致updateUIView()方法被调用?在@Binding和调用之间显然存在一些隐藏的连接,但是如何工作?

//  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 个答案:

答案 0 :(得分:1)

SwiftUI正在管理@State@Binding对象的内存,并自动刷新依赖您的变量的任何View的UI。 SwiftUI是封闭源代码,因此很遗憾,我们尚不知道该如何完成,但为简单起见,可以将其视为幕后的didSet修饰符。