是的,如果[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
的註釋可能會非常昂貴!