0

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

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

它工作正常。但是,当尝试在 View Stack 上显示其他 @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()调用)

有人对可能是什么问题有任何想法吗?或者我在这里错过了什么?

谢谢!

4

1 回答 1

2

感谢这篇文章,在这里回答我自己的问题

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)
}
于 2020-05-07T18:33:19.697 回答