问题描述
在iOS中8斯威夫特使用MapKit,我怎么使人们有可能在动画自定义注解的地图位置的改变?我这样说:
UIView.animateWithDuration(0.25){
无功禄= ann.coordinate
loc.latitude = loc.latitude + 0.0005
loc.longitude = loc.longitude + 0.001
ann.coordinate =禄
}
...其中安
是一个自定义的注释,MyAnnotation。注释是跳跃的,没有动画,新的坐标位置。
恼人的事情是,动画作品完美的如果我写在Objective-C 的MyAnnotation。但是,如果我把它写在斯威夫特,我没有得到任何动画更多!
仅供参考,这里是我的雨燕code为MyAnnotation:
类MyAnnotation:NSObject的,MKAnnotation {
VAR坐标:CLLocationCoordinate2D
VAR标题:串!
VAR字幕:串! 的init(坐标位置:CLLocationCoordinate2D){
self.coordinate =坐标
super.init()
}
}
您几乎都有它的权利!只要改变这条线在MyAnnotation实现:
VAR坐标:CLLocationCoordinate2D
这样:
动态无功协调:CLLocationCoordinate2D
这将修复它。
为什么这件事情?因为注解动画依赖于志愿(键值观察)。在斯威夫特,属性是不可观测,除非它被标记为键值动态
。 (为了得到多一点的技术,这又是因为志愿观测的工作方式是交叉混合属性setter方法的实现 - 运行时到达到您的权利类,并改变了该属性的setter code,但在雨燕,它可以。做T,除非你明确地标记属性作为动态
)
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? 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. 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. But if I write it in Swift, I don't get the animation any more!
Just FYI, here is my Swift code for MyAnnotation:
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:
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). In Swift, a property is not key value observable unless it is marked as 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
.)
这篇关于动画MapKit注释协调斯威夫特的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!