ContentView 中的按钮可缩放到 MapBox 地图上的当前位置?
所以......在我的协调器中-符合mapbox委托协议,我可以这样做:
So....in my coordinator--which conforms to the mapbox delegate protocol, I can just do:
mapView.setCenter(mapView.userLocation!.coordinate, zoomLevel: 13, animated: true)
,并且此函数在协调器中或在mapView类中调用时均能正常工作.唯一的问题是我不知道如何传递该mapView实例(特别是返回到ContentView中,我想要一个具有相同功能的按钮).我也有一个LocationManager结构,但是我不知道这里会有多少用处.传递MapView实例是完成我想做的最简单的方法吗?
and this function works fine in the coordinator or when it is called in the mapView class. The only problem is I don't know how to pass this mapView instance around (specifically back into ContentView where I want to have a button that does the same thing). I also have a LocationManager struct but I don't know how much use that would be here. Is the passing of the MapView instance the simplest way to accomplish what I'd like to do?
提前谢谢!
此处是解决方案的演示(基于MapKit,但对想法并不重要).经过Xcode 12测试.
Here is a demo of solution (based on MapKit, but it not important for idea). Tested with Xcode 12.
struct DemoActionToMapView: View {
@State private var centerToUser: () -> () = {}
var body: some View {
VStack {
Button("Center", action: centerToUser)
MapView { map in
self.centerToUser = {
map.setCenter(map.userLocation.coordinate, animated: true)
}
}
}
}
}
struct MapView: UIViewRepresentable {
var configure: (MKMapView) -> () = { _ in }
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
DispatchQueue.main.async {
configure(map)
}
return map
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
}