【发布时间】:2011-04-29 06:21:49
【问题描述】:
我在没有InterfaceBuilder 的情况下工作。
我有一个MKAnnotationView 的实例,setDraggable 在是上,
在 My MKMapView 中显示了我的注释视图,我可以拖放它。
执行放置操作时如何执行方法? 在这种方法中,我需要注释视图的新坐标。
【问题讨论】:
标签: iphone drag-and-drop ios mkmapview
我在没有InterfaceBuilder 的情况下工作。
我有一个MKAnnotationView 的实例,setDraggable 在是上,
在 My MKMapView 中显示了我的注释视图,我可以拖放它。
执行放置操作时如何执行方法? 在这种方法中,我需要注释视图的新坐标。
【问题讨论】:
标签: iphone drag-and-drop ios mkmapview
如果您使用 setCoordinate 方法正确设置了 MKAnnotation 对象,那么在 didChangeDragState 方法中,新坐标应该已经在注释对象中:
- (void)mapView:(MKMapView *)mapView
annotationView:(MKAnnotationView *)annotationView
didChangeDragState:(MKAnnotationViewDragState)newState
fromOldState:(MKAnnotationViewDragState)oldState
{
if (newState == MKAnnotationViewDragStateEnding)
{
CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
}
}
有关参考,请参阅docs here 中的“将注释视图标记为可拖动”部分。如果您的应用程序需要在 4.x 之前的操作系统中运行,则拖动需要更多的手动工作。文档中的链接还指向了一个示例,说明如何在需要时执行此操作。
【讨论】:
您可能还想添加以下内容:
if (newState == MKAnnotationViewDragStateStarting) {
annotationView.dragState = MKAnnotationViewDragStateDragging;
}
else if (newState == MKAnnotationViewDragStateEnding || newState == MKAnnotationViewDragStateCanceling) {
annotationView.dragState = MKAnnotationViewDragStateNone;
}
因为 MKAnnotationView 不会准确更改其拖动状态(即使在您停止拖动后,这也可能使您的地图随注释一起平移)
【讨论】:
快速解决方案:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState)
{
if (newState == MKAnnotationViewDragState.ending)
{
let droppedAt = view.annotation?.coordinate
print("dropped at : ", droppedAt?.latitude ?? 0.0, droppedAt?.longitude ?? 0.0);
view.setDragState(.none, animated: true)
}
if (newState == .canceling )
{
view.setDragState(.none, animated: true)
}
}
【讨论】: