Jason G
Jason G

Reputation: 2733

custom MKAnnotation not moving when coordinate set

I've got a custom MKAnnotation set up

class Location: NSObject, MKAnnotation {
    var id: Int
    var title: String?
    var name: String

    var coordinate: CLLocationCoordinate2D {
        didSet{
            didChangeValueForKey("coordinate")
        }
    }

when i set the coordinate it does not move the pin on the map. I added the 'didSet' with the key word coordinate as i found people saying that would force it to update. but nothing, it doesn't move. i have verified the lat / long have changed and are correct, the pin just isn't moving. Title updates and displays the change.

i have to assume its because this is a custom annotation. any help?

Upvotes: 8

Views: 1763

Answers (1)

Rob
Rob

Reputation: 437372

If you're going to manually post those change events, you have to call willChangeValue(forKey:) in willSet, too. In Swift 4:

var coordinate: CLLocationCoordinate2D {
    willSet {
        willChangeValue(for: \.coordinate)
    }
    didSet {
        didChangeValue(for: \.coordinate)
    }
}

Or in Swift 3:

var coordinate: CLLocationCoordinate2D {
    willSet {
        willChangeValue(forKey: #keyPath(coordinate))  
    }
    didSet {
        didChangeValue(forKey: #keyPath(coordinate))
    }
}

Or, much easier, just specify it as a dynamic property and this notification stuff is done for you.

@objc dynamic var coordinate: CLLocationCoordinate2D

For Swift 2 version, see previous rendition of this answer.

Upvotes: 19

Related Questions