Update the title of an MKAnnotation

Sep 17, 2015 · Follow on Twitter and Mastodon swiftmapkitgeo

I’m building a map app where users can save pins and present them as custom pins, with custom icons and colors. I must therefore update how MKAnnotation is shown on a map.

When the user taps a pin on the map, the app will reverse geocode its coordinate and use it to display the full address in the callout subtitle.

iOS Simulator Screen

This may seem trivial, but was actually a hassle. If the geocoding operation takes too long and completes after the callout has been shown, the label text is not changed.

Turns out you have to add some code to make this work. Instead of just setting the subtitle, you must tell the app that you will change it, change it, then tell it that you have changed it.

The code for this becomes:

myAnnotation.willChangeValueForKey("subtitle")
myAnnotation.subtitle = "An address somewhere in the world"
myAnnotation.didChangeValueForKey("subtitle")

As soon as I added this extra piece of code to the app, the reverse geocoder could update the subtitle without problems, even when the operation took some time.

Since my annotations inherit a class called MapAnnotation, I specified the subtitle as such:

var subtitle: String? {
   willSet { willChangeValueForKey("subtitle") }
   didSet { didChangeValueForKey("subtitle") }
}

This triggers the events in correct order, every time the subtitle property value is changed.

Discussions & More

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon.

If you found this text interesting, make sure to follow me on Twitter and Mastodon for more content like this, and to be notified when new content is published.

If you like & want to support my work, please consider sponsoring me on GitHub Sponsors.