如何将Mapbox SDK与SwiftUI集成 [英] How to integrate Mapbox SDK with SwiftUI
问题描述
我将Mapbox SDK安装到了我的项目中,但是我不明白如何将此代码段与 SwiftUI
集成.
I installed the Mapbox SDK into my project, but I don't understand how to integrate this code snippet with SwiftUI
.
我创建了一个名为 MapView
的SwiftUI View
,并在其中导入了Mapbox Framework.
I created a SwiftUI View
named MapView
, where I import the Mapbox Framework.
我尝试像Apple教程中那样使用 UIViewRepresentable
协议,但没有成功.
I try to use the UIViewRepresentable
protocol, as in Apple's tutorial, but without success.
import Mapbox
class MapView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let styleURL = URL(string: "mapbox://styles/mapbox/outdoors-v9")
let mapView = MGLMapView(frame: view.bounds,
styleURL: styleURL)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 45.52954,
longitude: -122.72317),
zoomLevel: 14,
animated: false)
view.addSubview(mapView)
}
}
我是iOS开发的新手,所以将不胜感激.
I am new to iOS development, so any help would be much appreciated.
推荐答案
这是一个有效的示例,说明如何将 MGLMapView
与 SwiftUI
集成.
This is a working sample on how you can integrate the MGLMapView
with SwiftUI
.
使用 UIViewRepresentable
时,必须实现两个委托: makeUIView
将返回您的视图(在本例中为 MGLMapView
)和updateUIView
,它将获得与 makeUIView
中返回的视图类型相同的视图类型(同样是 MGLMapView
).
When using UIViewRepresentable
you have to implement two delegates: makeUIView
that will return your view (in this case MGLMapView
) and updateUIView
which will receive the same view type as the one returned in makeUIView
(again MGLMapView
).
您可以使用它进行实验.
You can use this to experiment.
我还建议您熟悉React架构,以更好地了解SwiftUI方法.
Also I recommend you get familiar with the React architecture to understand better the SwiftUI approach.
您可以通过使 ContentView
接收styleURL并在预览中尝试不同的样式来改进此示例.
You can improve this sample by making ContentView
receive a styleURL, and trying different styles in the preview.
import Mapbox
import SwiftUI
struct ContentView : View {
var body: some View {
MapboxViewRepresentation(MGLStyle.streetsStyleURL)
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
struct MapboxViewRepresentation : UIViewRepresentable {
let styleURL: URL
init(_ styleURL: URL) {
self.styleURL = styleURL
}
func makeUIView(context: UIViewRepresentableContext<MapboxViewRepresentation>) -> MGLMapView {
let mapView = MGLMapView(frame: .zero, styleURL: styleURL)
return mapView
}
func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapboxViewRepresentation>) {
}
}
更新:这是有关如何将Mapbox与SwiftUI集成的官方指南 https://docs.mapbox.com/help/tutorials/ios-swiftui/
UPDATE: Here is the official guide on how to integrate Mapbox with SwiftUI https://docs.mapbox.com/help/tutorials/ios-swiftui/
这篇关于如何将Mapbox SDK与SwiftUI集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!