在Swift中动画MapKit注释坐标变化?

mat*_*att 22 animation mapkit mkannotation ios swift

在Swift的iOS 8中使用MapKit时,如何设置自定义注释的地图位置变化的动画?我这样说:

UIView.animateWithDuration(0.25) {
    var loc = ann.coordinate
    loc.latitude = loc.latitude + 0.0005
    loc.longitude = loc.longitude + 0.001
    ann.coordinate = loc
}
Run Code Online (Sandbox Code Playgroud)

... ann自定义注释MyAnnotation在哪里.注释是跳跃而不是动画,到新的坐标位置.

令人讨厌的是,如果我在Objective-C中编写MyAnnotation,动画效果很好.但如果我在Swift中编写它,我就不再动画了!

仅供参考,这是我的MyAnnotation的Swift代码:

class MyAnnotation : NSObject, MKAnnotation {
    var coordinate : CLLocationCoordinate2D
    var title: String!
    var subtitle: String!

    init(location coord:CLLocationCoordinate2D) {
        self.coordinate = coord
        super.init()
    }
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 63

你几乎把它弄好了!只需在MyAnnotation实现中更改此行:

var coordinate : CLLocationCoordinate2D
Run Code Online (Sandbox Code Playgroud)

对此:

dynamic var coordinate : CLLocationCoordinate2D
Run Code Online (Sandbox Code Playgroud)

这将解决它.

为什么这很重要?因为注释动画依赖于KVO(键值观察).在Swift中,除非标记为属性,否则属性不是可观察的键值dynamic.(为了获得更多的技术,反过来是因为KVO观察通过调配属性setter方法的实现来工作 - 运行时到达你的类并更改该属性的setter代码.但是在Swift中,它无法做到这一点除非您明确将该属性标记为dynamic.)