gpt4 book ai didi

swift - 如何将 Mapbox SDK 与 SwiftUI 集成

转载 作者:可可西里 更新时间:2023-11-01 00:54:05 25 4
gpt4 key购买 nike

我在我的项目中安装了 Mapbox SDK,但我不明白如何将此代码片段与 SwiftUI 集成。

我创建了一个名为 MapView 的 SwiftUI View,我在其中导入了 Mapbox Framework。

我尝试使用 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 开发的新手,所以非常感谢任何帮助。

最佳答案

这是一个关于如何将 MGLMapViewSwiftUI 集成的工作示例。

当使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com