UIViewRepresentableView中的绑定破坏了ObservableObject功能

时间:2019-12-07 14:21:20

标签: ios swift swiftui

我有一个为我创建MKMapView的UIViewRepresentableView。我正在使用两个ObservedObjects处理用户可以放下的销钉并跟踪当前位置。到目前为止一切正常。但是,如果另外向我的ContentView的状态(用于保存地图视图的状态)插入一个Binding,则ObservableObjects的@Published属性上的更改不会导致地图视图刷新。我真的不明白为什么会这样...

我的ContentView包含UIViewRepresentable MapView

struct ContentView: View {

@State var showPhotos = false
@ObservedObject var regionManager: LocationManager
@ObservedObject var annotationManager: AnnotationManager

var body: some View {
    NavigationView {
        ZStack(alignment: .bottomTrailing) {
            MyMap(showPhotos: $showPhotos, locationManager: regionManager, annotationManager: annotationManager)
            Button(action: {
                self.regionManager.goToUserLocation()
            }) {
                LocationButton()
            }
        }
            .edgesIgnoringSafeArea(.bottom)
            .navigationBarTitle("Long-press to select location", displayMode: .inline)
    }
}

}

我的实际MapView

struct MyMap: UIViewRepresentable {

@Binding var showPhotos: Bool

@ObservedObject var locationManager: LocationManager
@ObservedObject var annotationManager: AnnotationManager

func makeCoordinator() -> MyMap.Coordinator {
    Coordinator(self)
}

func makeUIView(context: Context) -> MKMapView {

    let map = MKMapView()
    map.delegate = context.coordinator
    context.coordinator.map = map

    locationManager.configureUserLocation()
    map.showsUserLocation = true

    map.setRegion(locationManager.currentRegion, animated: true)

    let longPress = UILongPressGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.didLongPress(gesture:)))
    longPress.minimumPressDuration = 1.0
    map.addGestureRecognizer(longPress)

    return map
}

func updateUIView(_ map: MKMapView, context: Context) {

    if annotationManager.currentAnnotation != nil {
        map.removeAnnotations(map.annotations)
        map.addAnnotation(annotationManager.currentAnnotation!)
    }

    map.setRegion(locationManager.currentRegion, animated: true)
}

class Coordinator: NSObject, MKMapViewDelegate, CLLocationManagerDelegate {

    var parent: MyMap
    var map: MKMapView?

    init(_ parent: MyMap) {
        self.parent = parent
    }

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        parent.showPhotos = true
    }

    @objc func didLongPress(gesture: UITapGestureRecognizer) {
        //...
    }


}

}

0 个答案:

没有答案