简体   繁体   English

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

[英]Animate MapKit annotation coordinate change in Swift?

When using MapKit in iOS 8 in Swift, how do I make it possible to animate a change in the map position of a custom annotation? 在Swift的iOS 8中使用MapKit时,如何设置自定义注释的地图位置变化的动画? I am saying this: 我这样说:

UIView.animateWithDuration(0.25) {
    var loc = ann.coordinate
    loc.latitude = loc.latitude + 0.0005
    loc.longitude = loc.longitude + 0.001
    ann.coordinate = loc
}

...where ann is a custom annotation, MyAnnotation. ...其中ann是自定义注释,MyAnnotation。 The annotation is jumping, not animating, to the new coordinate position. 注释是跳跃而不是动画,到新的坐标位置。

The annoying thing is that the animation works perfectly if I write MyAnnotation in Objective-C . 令人讨厌的是, 如果我在Objective-C中编写MyAnnotation,动画效果很好。 But if I write it in Swift, I don't get the animation any more! 但如果我在Swift中编写它,我就不再动画了!

Just FYI, here is my Swift code for MyAnnotation: 仅供参考,这是我的MyAnnotation的Swift代码:

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

    init(location coord:CLLocationCoordinate2D) {
        self.coordinate = coord
        super.init()
    }
}

You almost have it right! 你几乎把它弄好了! Just change this line in your MyAnnotation implementation: 只需在MyAnnotation实现中更改此行:

var coordinate : CLLocationCoordinate2D

to this: 对此:

dynamic var coordinate : CLLocationCoordinate2D

That will fix it. 这将解决它。

Why does this matter? 为什么这很重要? Because annotation animation relies on KVO (key value observing). 因为注释动画依赖于KVO(键值观察)。 In Swift, a property is not key value observable unless it is marked as dynamic . 在Swift中,属性不是可观察的键值,除非它被标记为dynamic (To get a little more technical, that in turn is because KVO observation works by swizzling the implementation of the property setter method - the runtime reaches right into your class and changes that property's setter code. But in Swift, it can't do that unless you explicitly mark the property as dynamic .) (为了获得更多的技术,反过来是因为KVO观察通过调配属性setter方法的实现来工作 - 运行时到达你的类并更改该属性的setter代码。但是在Swift中,它无法做到这一点除非您明确将该属性标记为dynamic 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM