是什么导致在此代码中调用updateUIView()? [英] What causes updateUIView() to be called in this code?

查看:33
本文介绍了是什么导致在此代码中调用updateUIView()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()
    }
}

推荐答案

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

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.

这篇关于是什么导致在此代码中调用updateUIView()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆