2

Is there a way to update custom MKAnnotationView after change to custom MKAnnotation data? Is this where observers come into play (haven't used these before).

Currently for example I am doing the following manually:

In my custom MKAnnotation after making changes to data:

let annView: GCCustomAnnotationView = self.mapView.viewForAnnotation(annotation) as! GCCustomAnnotationView
annView.updateText()  

In my custom MKAnnotationView:

func updateText() {
    let gcAnnotation : GCAnnotation = self.annotation as! GCAnnotation
    calloutView.line1.text = gcAnnotation.locality
    calloutView.line2.text = gcAnnotation.sublocality
    calloutView.line3.text = gcAnnotation.name
}
Greg
  • 34,042
  • 79
  • 253
  • 454

1 Answers1

3

You could implement KVO to observe changes in the annotation's data. That is the mechanism that is used by the MKAnnotationView class to observe changes in the coordinate property of MKAnnotation. Standard Swift doesn't use KVO, it is more of a ObjectiveC leftover thing and a bit of a hassle to implement in Swift. A simple solution I used is to call setNeedsDisplay on the custom annotation view when the annotation's data has changed. This causes drawRect to be called. Within your implementation of drawRect you can then poll the annotation's data (as you do in your code snippet) to change the appearance of the view.

So long story short, when your data changes:

annView.setNeedsDisplay()

is all you need in your case.

Then within your drawRect implementation of your subclassed MKAnnotationView instance you call your updateText function:

override func draw(_ rect: CGRect) {
    updateText()
    // etc.
}
Zoef
  • 228
  • 2
  • 13