Mapbox + SwiftUI: пользовательский интерфейс Refre sh не распространяется - PullRequest
0 голосов
/ 19 марта 2020

Я интегрировал Mapbox с SwiftUI, используя следующий пример:

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

Работает нормально. Однако при попытке отобразить другие переменные @State в стеке просмотра распространение пользовательского интерфейса Refre sh прекращает переход к вызову 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)") обновляется - однако аннотации не обновляются (следовательно, updateUIView() не вызывается).

Если я прокомментирую // Text("\(self.annotations.count)"), то аннотации обновляются (и вызывается updateUIView())

У кого-нибудь есть идеи о том, в чем может быть проблема? Или я что-то здесь упускаю?

Спасибо!

1 Ответ

1 голос
/ 07 мая 2020

Отвечая на мой собственный вопрос здесь благодаря этому сообщению

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

Чтобы это работало, необходимо обновить отображаемый UIView внутри Mapview:

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)
}
...