swift - 如何将 Mapbox SDK 与 SwiftUI 集成

标签 swift mapbox swiftui

我在项目中安装了 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 开发新手,因此我们将不胜感激。

最佳答案

这是一个关于如何将 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/

相关文章:

swift - Apple Pencil 笔颜色比 PKInkingTool 指定的颜色深

mapbox gl setFilter 按indexOf、包含或子字符串过滤

leaflet - 在 MapBox 中加载 geoJson 以使用 Leaflet.Draw 进行编辑

android - 解析 XML 时出错 : unbound prefix for mapbox

使用 SegmentedPickerStyle 的 Picker 内的 SwiftUI 自定义字体大小

swiftui - 如何在 macOS 上使用 SwiftUI 显示 QLPreviewPanel?

ios - 函数未在委托(delegate)方法内调用 - IOS/Swift

iOS 扩展 - 致命异常 : com. firebase.core 默认应用已配置

ios - 我错过了什么??解包时发现 fatal error 意外 nil

ios - SwiftUI 中的@Binding 和 ForEach