我在项目中安装了 Mapbox SDK,但我不明白如何将此代码片段与 SwiftUI
集成。
我创建了一个名为 MapView
的 SwiftUI View
,我在其中导入了 Mapbox 框架。
我尝试使用 UIViewRepresentable
协议(protocol),如 Apple 教程中所示,但没有成功。
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 开发新手,因此我们将不胜感激。
最佳答案
这是一个关于如何将 MGLMapView
与 SwiftUI
集成的工作示例。
使用UIViewRepresentable
时,您必须实现两个委托(delegate):makeUIView
,它将返回您的 View (在本例中为MGLMapView
)和 updateUIView
它将接收与 makeUIView
中返回的 View 类型相同的 View 类型(同样是 MGLMapView
)。
您可以用它来进行实验。
此外,我建议您熟悉 React 架构,以便更好地理解 SwiftUI 方法。
您可以通过使 ContentView
接收 styleURL 并在预览中尝试不同的样式来改进此示例。
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/
关于swift - 如何将 Mapbox SDK 与 SwiftUI 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56551145/