custom MKAnnotation not moving when coordinate set

空扰寡人 提交于 2019-12-07 01:34:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34475342/custom-mkannotation-not-moving-when-coordinate-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!