2016-07-26 51 views
0

我想点击一个MKAnnotationView时MapkKit使用下面的代码显著放大一针:MKAnnotationView取消对setRegion

MKCoordinateRegion mapRegion; 
    mapRegion.center = view.annotation.coordinate;; 
    mapRegion.span.latitudeDelta = 0.2; 
    mapRegion.span.longitudeDelta = 0.2; 

    [MKMapView animateWithDuration:0.15 animations:^{ 
     [mapView setRegion:mapRegion animated: YES]; 
    }]; 

但是,每当我在我放大想要的引脚保持选中状态。有没有办法阻止MKAnnotatiotionView被取消选择,并且函数didDeselectAnnotationView不被调用。

我认为它可能发生的原因是因为缩放的mapView正在更新注释。有没有办法来防止这种情况发生?

回答

0

是的,如果[mapView setRegion: ...]导致mapView上的注释因任何原因而改变,那么您选择的注释将被取消选择(因为它将要被移除!)。

解决此问题的一种方法是对您的注释进行“差异”替换。例如,此刻,你可能有一些代码,看起来像(斯威夫特表示):

func displayNewMapPins(pinModels: [MyCustomPinModel]) { 
    self.mapView.removeAnnotations(self.mapView.annotations) //remove all of the currently displayed annotations 

    let newAnnotations = annotationModels.map { $0.toAnnotation } //convert 'MyCustomPinModel' to an 'MKAnnotation' 
    self.mapView.addAnnotations(newAnnotations) //put the new annotations on the map 
} 

你想改变它,更是这样的:

func displayNewMapPins(pinModels: [MyCustomPinModel]) { 
    let oldAnnotations = self.mapView.annotations 
    let newAnnotations = annotationModels.map { $0.toAnnotation } 

    let annotationsToRemove = SomeOtherThing.thingsContainedIn(oldAnnotations, butNotIn: newAnnotations) 
    let annotationsToAdd = SomeOtherThing.thingsContainedIn(newAnnotations, butNotIn: oldAnnotations) 

    self.mapView.removeAnnotations(annotationsToRemove) 
    self.mapView.addAnnotations(annotationsToAdd) 
} 

SomeOtherThing.thingsContainedIn(:butNotIn:)确切实施取决于您的要求,但这是您希望实现的通用代码结构。

这样做会提高您的应用程序的性能 - 添加和删除MKMapView的注释可能会非常昂贵!