当使用自定义初始化程序的结构实例为 运行 时,如何定义应该 运行 的自定义闭包(SwiftUI)

How to define a custom closure that should run when an instance of a struct that uses a custom initializer is run (SwiftUI)

所以在 MapView 中,我需要一个定义如下的自定义初始化器。

import SwiftUI
import Mapbox

struct MapView: UIViewRepresentable {
    var configure: (MGLMapView) -> () = { _ in }
    @Binding var showMoreDetails: Bool
    var VModel: ViewModel
    var token: String

    init(showMoreDetails: Binding<Bool>, VModel: ViewModel, token: String) {
        self.VModel = VModel
        self.token = token
        _showMoreDetails = showMoreDetails
    }

    //This function creates the actual view of the map
    func makeUIView(context: Context) -> MGLMapView {
        let map = MGLMapView()
        DispatchQueue.main.async {
            map.delegate = context.coordinator
            self.configure(map)
        }
        return map
    }

    //This function is called whenever there is a change in the map's state
    //Go over the functionality of this with TJ.
    func updateUIView(_ uiView: MGLMapView, context: Context) {   
    }
}

在 ContentView 中,我想按如下方式初始化视图:

import SwiftUI
import Mapbox

struct ContentView: View {
    @ObservedObject var VModel: ViewModel = ViewModel()
    @State private var showMoreDetails: Bool = true
    @State private var token: String = "test"
    @State private var centerToUser: () -> () = { }
    var body: some View {
        ZStack {
        MapView(showMoreDetails: $showMoreDetails, VModel: VModel, token: token) { map in
                    self.centerToUser = {
                        print("run code!")
                    }
                }
        Button("test", action: centerToUser)
        }
    }
}

我认为问题出在我在 MapView 结构中定义的自定义初始值设定项中——当我在 ContentView 中删除它旁边的闭包时,它会起作用。我如何编辑自定义初始化程序,以便它在初始化 MapView 时也接受闭包?

如果您添加显式初始化程序,那么您要配置的所有属性也应该在该初始化程序中

所以解决方案是

struct MapView: UIViewRepresentable {
    @Binding var showMoreDetails: Bool
    var VModel: ViewModel
    var token: String
    var configure: (MGLMapView) -> ()       // declare

    init(showMoreDetails: Binding<Bool>, VModel: ViewModel, token: String, 
                        configure: @escaping (MGLMapView) -> () = { _ in }) { // last
        self.VModel = VModel
        self.token = token
        self.configure = configure           // << initialize !!
        _showMoreDetails = showMoreDetails
    }

    // .. other code