如何在添加新的注释针时删除先前的注释针?

3

我有一个UITableView,每个单元格都包含一个地图按钮。当我点击每个按钮时,地图视图会显示并添加相应的注释标记。

当我点击每个地图按钮时,调用此代码:

    double tempLatitude  = [[[myDict objectForKey:key] objectAtIndex:15] doubleValue];
    double tempLongitude = [[[myDict objectForKey:key] objectAtIndex:16] doubleValue];
                                                  // key is the cell index.

         //--** Setting the Latitude and Longitude 
         CLLocationCoordinate2D myCoordinate;

         myCoordinate.latitude  = tempLatitude;
         myCoordinate.longitude = tempLongitude;

         MyMapAnnotation *MyAnnotation = [[[MyMapAnnotation alloc] initWithCoordinate:myCoordinate addressDictionary:nil]autorelease];
         MyAnnotation.title            = [[myDict objectForKey:key] objectAtIndex:1];
         MyAnnotation.subtitle         = [NSString  stringWithFormat:@"%f %f", MyAnnotation.coordinate.latitude, MyAnnotation.coordinate.longitude];

这是MyMapAnnotation的代码:

    @synthesize coordinate = theCoordinate;
    @synthesize title = theTitleAnnotation;
    @synthesize subtitle = theSubTitleAnnotation;



    - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate addressDictionary:(NSDictionary *)addressDictionary 
    {

      if ((self = [super initWithCoordinate:coordinate addressDictionary:addressDictionary]))
      {
         self.coordinate = coordinate;
      }
         return self;
    }

一切都运作良好。现在,当我点击一个按钮时,相应的注释针会显示出来,当我点击第二个按钮时,之前的针仍然存在,并且第二个注释针也被添加了。
但是,
我想要的是,
每当我点击一个按钮时,之前的注释针应该被移除,只有当前的注释针应该被添加。
我怎样才能识别出之前的针?
在哪里可以给出这段代码 [mapView removeAnnotation:annotationToRemove] ??
编辑:显然,“之前的注释针”就是“annotationToRemove”。我知道这一点。我的问题是,我怎样才能识别出这个之前的注释针以指定为“annotationToRemove”??
谢谢 :-)

如果您在另一个视图中点击显示地图视图的单元格? - Aravindhan
你尝试过使用 [myMap removeAnntoation:[myMap.annotations objectAtIndex:0]; 吗? - Mat
@Mat,那是正确的答案.. :) 你能把它写成答案吗,这样我就可以接受了。非常感谢 :) - S.Philip
5个回答

7

你尝试过使用[myMap removeAnntoation:[myMap.annotations objectAtIndex:0]];吗?

编辑: 有几种方法可以实现这个功能,一种是给注释设置一个tag,然后通过标签搜索;另一种方法是检查所有的注释,然后删除你想要的那个。如果你的问题是删除之前添加的注释,你可以调用:

[myMap removeAnntoation:[myMap.annotations lastObject]];

附:如果你设置了myMap.showsUserLocation=YES;,请参考:如何从MKMapView中删除所有注释而不删除蓝点?


1
我通过在添加下一个注释标记之前加入以下代码来解决了问题:if([self.mapView.annotations count] == 1) { [self.mapView removeAnnotation:[self.mapView.annotations objectAtIndex:0]]; } 。谢谢 :) - S.Philip
作为我的附言,如果您在地图视图上显示用户位置,则“if”可能是真实的,即使您没有添加注释,但只有用户位置注释(蓝色圆圈)...干杯! - Mat

1
如果您想在另一个视图中显示地图视图,只需使用以下代码:
-(void)viewWillappear
{
[myMap removeAnnotations:toRemove];
}

但它不是另一个视图。它是出现在同一视图控制器中的UIView。我的疑问是,要给什么作为“toRemove”?如何识别先前的注释? :) - S.Philip
你正在使用哪些类? - Aravindhan
非常感谢您的帮助.. :) @Mat 给出了正确的答案。 - S.Philip

1
您可以使用 [MyAnnotation setHidden:YES]; 将标注关闭,稍后再次打开它。

0

试一下这个

-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view 
{
   [mapView removeAnnotation:annotationToRemove]
}

0

这个对我在Swift 5上起作用:

mapView.removeAnnotations([mapView.annotations].last)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接