OGeek|极客世界-中国程序员成长平台

标题: ios - 启用和禁用注释拖动(动态)(iOS Mapkit) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:51
标题: ios - 启用和禁用注释拖动(动态)(iOS Mapkit)

我创建了一个 map View ,它有一个按钮,可以根据项目要求在“编辑”模式和“拖动”模式之间切换。我意识到,通过在 viewForAnnotation 中将注释设置为可拖动,可以很容易地从创建中拖动注释,但所需的行为不允许这样做。我尝试了几种不同的方法将注释更改为可拖动但没有成功。第一个想法是遍历现有注释并将每个注释设置为“可拖动”和“已选择”,但我收到一个无法识别的选择器发送到实例错误(我确实尝试实例化一个新注释以传递对象并重新绘制虽然在循环中,但我也得到了同样的错误):

NSLog(@"Array Size: %@", [NSString stringWithFormat"%i", [mapView.annotations count]]);

    for(int index = 0; index < [mapView.annotations count]; index++) {

        if([[mapView.annotations objectAtIndex:index]isKindOfClass:[locAnno class]]){
            NSLog(@"** Location Annotation at Index: %@", [NSString stringWithFormat"%i", index]);
            NSLog(@"* Location Marker: %@", [mapView.annotations objectAtIndex:index]);
        }

        if([[mapView.annotations objectAtIndex:index]isKindOfClass:[hydAnno class]]) {
            NSLog(@"** Hydrant Annotation at Index: %@", [NSString stringWithFormat"%i", index]);
            NSLog(@"* Hydrant Marker: %@", [mapView.annotations objectAtIndex:index]);

            [[mapView.annotations objectAtIndex:index]setSelected:YES];
            [[mapView.annotations objectAtIndex:index]setDraggable:YES];
        }
    }

第二个想法是使用'didSelectAnnotationView',并在注释被选中时设置选定和可拖动,并在模式再次切换回来时重置属性。这很有效,但效果很差,因为事件并不总是触发,并且您的左键点击注释一次或多次,然后它会更改属性:

- (void)mapViewMKMapView *)mapView didSelectAnnotationViewMKAnnotationView *)view {
NSLog(@"Annotation Selected!");
if(!editMode) {
    view.selected = YES;
    view.draggable = YES;
}

}

如果我能让它工作,第一次尝试似乎是最简单的解决方案。另一方面,使用 didSelect 方法既麻烦又难搞。我对 iOS 开发很陌生,所以如果我在讨论这个问题时忽略了一些新手,我深表歉意。我感谢社区可以提供的任何见解。非常感谢。



Best Answer-推荐答案


第一种方法比使用didSelectAnnotationView委托(delegate)方法好。

导致“无法识别的选择器”错误的代码的问题是它在注释对象上调用 setSelected:setDraggable: ) 而不是它们对应的 MKAnnotationView 对象。 id 对象没有这样的方法,因此您会收到“无法识别的选择器”错误。

map View 的 annotations 数组包含对 id (数据模型)对象的引用——而不是那些的 MKAnnotationView 对象注释。

所以你需要改变这个:

[[mapView.annotations objectAtIndex:index]setSelected:YES];
[[mapView.annotations objectAtIndex:index]setDraggable:YES];

到这样的事情:

//Declare a short-named local var to refer to the current annotation...
id<MKAnnotation> ann = [mapView.annotations objectAtIndex:index];

//MKAnnotationView has a "selected" property but the docs say not to set
//it directly.  Instead, call deselectAnnotation on the annotation...
[mapView deselectAnnotation:ann animated:NO];

//To update the draggable property on the annotation view, get the 
//annotation's current view using the viewForAnnotation method...
MKAnnotationView *av = [mapView viewForAnnotation:ann];
av.draggable = editMode;


您还必须更新 viewForAnnotation delegate 方法中的代码,以便它还将 draggable 设置为 editMode 而不是硬编码 YESNO 以便如果 map View 需要为注释重新创建 View after 您已经更新了它在 for 循环中,注释 View 将具有 draggable 的正确值。

关于ios - 启用和禁用注释拖动(动态)(iOS Mapkit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9995197/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4