Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Jason G Avatar asked Dec 26 '15 21:12

Jason G


1 Answers

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.

like image 120
Rob Avatar answered Oct 26 '22 20:10

Rob