Mapbox + SwiftUI: UI 刷新不传播

Mapbox + SwiftUI: UI Refresh not propagating

我已经使用以下示例将 Mapbox 与 SwiftUI 集成:

https://github.com/mapbox/mapbox-maps-swiftui-demo

它工作正常。但是,当尝试在视图堆栈上显示其他 @State 变量时,UI 刷​​新传播停止向下调用 Mapbox updateUIView()

例如,您可以通过将上述存储库中的 ContentView.swift 替换为以下代码来重现该问题:

import SwiftUI
import Mapbox

struct ContentView: View {

    @State var annotations: [MGLPointAnnotation] = [
        MGLPointAnnotation(title: "Mapbox", coordinate: .init(latitude: 37.791434, longitude: -122.396267))
    ]

    var body: some View {
        ZStack {
            VStack {
                MapView(annotations: $annotations).centerCoordinate(.init(latitude: 37.791293, longitude: -122.396324)).zoomLevel(16)
                Button(action: {
                    let rand = Float.random(in: 37.79...37.80)
                    self.annotations.append(MGLPointAnnotation(title: "Mapbox", coordinate: .init(latitude: CLLocationDegrees(rand), longitude: -122.396261)))
                }) {
                    Text("Button")
                    Text("\(self.annotations.count)")
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

运行 上面的代码表明 Text("\(self.annotations.count)") UI 得到了更新——但是,注释没有被刷新(因此 updateUIView() 没有被调用)。

如果我评论 // Text("\(self.annotations.count)") 那么注释会被刷新(并且 updateUIView() 被调用)

有人知道问题出在哪里吗?或者我在这里遗漏了什么?

谢谢!

感谢这个post

在这里回答我自己的问题

https://github.com/mapbox/mapbox-maps-swiftui-demo/issues/3#issuecomment-623905509

为了使其正常工作,有必要更新在 Mapview 中呈现的 UIView:

func updateUIView(_ uiView: MGLMapView, context: Context) {
    updateAnnotations(uiView)
    trackUser()
}

private func updateAnnotations(_ view: MGLMapView) {
    if let currentAnnotations = view.annotations {
        view.removeAnnotations(currentAnnotations)
    }
    view.addAnnotations(annotations)
}