【发布时间】:2014-03-01 06:48:46
【问题描述】:
我正在学习在我刚刚起步的 iOS 应用中使用 MapKit。我正在使用我的一些模型实体作为注释(将<MKAnnotation> 协议添加到它们的头文件中)。我还创建了自定义 MKAnnotationViews 并将draggable 属性设置为YES。
我的模型对象有一个location 属性,即CLLocation*。为了符合<MKAnnotation> 协议,我在该对象中添加了以下内容:
- (CLLocationCoordinate2D) coordinate {
return self.location.coordinate;
}
- (void) setCoordinate:(CLLocationCoordinate2D)newCoordinate {
CLLocation* newLocation = [[CLLocation alloc]
initWithCoordinate: newCoordinate
altitude: self.location.altitude
horizontalAccuracy: self.location.horizontalAccuracy
verticalAccuracy: self.location.verticalAccuracy
timestamp: nil];
self.location = newLocation;
}
- (NSString*) title {
return self.name;
}
- (NSString*) subtitle {
return self.serialID;
}
所以,我有 4 个必需的方法。而且它们非常简单。当我在MKAnnotationView 和@draggable 属性上阅读苹果文档时,它显示以下内容:
将此属性设置为 YES 使用户可以拖动注释。如果是,关联的注解对象也必须实现 setCoordinate: 方法。此属性的默认值为 NO。
在其他地方,MKAnnotation 文档说:
您对该属性的实现必须符合键值观察 (KVO)。有关如何实现对 KVO 的支持的更多信息,请参阅 Key-Value Observing Programming Guide。
我已经阅读了那个(简短的)文档,我完全不清楚我应该做些什么来完成它,所以我从我的location 属性派生的coordinate 是本身就是一个适当的属性。
但我有理由确定它不能正常工作。当我拖动图钉时,它会移动,但是当我平移地图时它不再重新定位。
更新
所以我尝试使用股票 MKPinAnnotationView。为此,我简单地注释掉了我的委托的mapView:viewForAnnotation: 方法。我发现这些默认情况下是不可拖动的。我将mapView:didAddAnnotationViews: 添加到我的委托中,以将添加的视图的draggable 属性设置为YES。
一旦如此配置,Pin 视图(如下面的 John Estropia 所暗示)似乎可以正常工作。我决定使用mapView:annotationView:didChangeDragState:fromOldState:委托钩子来仔细看看发生了什么:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
NSArray* states = @[@"None", @"Starting", @"Dragging", @"Cancelling", @"Ending"];
NSLog(@"dragStateChangeFrom: %@ to: %@", states[oldState], states[newState]);
}
对于库存引脚,您将看到如下所示的日志输出:
2014-02-05 09:07:45.924 myValve[1781:60b] dragStateChangeFrom: None to: Starting
2014-02-05 09:07:46.249 myValve[1781:60b] dragStateChangeFrom: Starting to: Dragging
2014-02-05 09:07:47.601 myValve[1781:60b] dragStateChangeFrom: Dragging to: Ending
2014-02-05 09:07:48.006 myValve[1781:60b] dragStateChangeFrom: Ending to: None
这看起来很合乎逻辑。但是如果你切换到配置的MKAnnotationView,你会看到的输出是这样的:
2014-02-05 09:09:41.389 myValve[1791:60b] dragStateChangeFrom: None to: Starting
2014-02-05 09:09:45.451 myValve[1791:60b] dragStateChangeFrom: Starting to: Ending
它错过了两个转换,从开始到拖动,从结束到无。
所以我开始怀疑我需要对属性做一些不同的事情。但我仍然对为什么这不起作用感到沮丧。
更新 2
我创建了我自己的 Annotation 对象来站在我的模型对象之间,它可能有一个属性 coordinate 属性。行为保持不变。这似乎与MKAnnotationView有关。
【问题讨论】:
-
@Anna 这帮助很大,谢谢。我不是子类化,但这个想法大部分是相同的。我几乎让它工作了。我将发布我的解决方案,并提出一个新问题。
标签: ios properties ios7 mapkit key-value-observing