Ios 如何删除地图视图上的最后一个注释
我在.xib文件上添加了一个按钮,希望用它删除最后添加的注释 因此,在着陆行动中,我实施了以下措施:Ios 如何删除地图视图上的最后一个注释,ios,mkmapview,mapkit,mkannotation,Ios,Mkmapview,Mapkit,Mkannotation,我在.xib文件上添加了一个按钮,希望用它删除最后添加的注释 因此,在着陆行动中,我实施了以下措施: -(IBAction)DeleteAnnotation:(id)sender { [mapview removeAnnotation:[mapview.annotations lastObject]]; } 我甚至试过这样做: -(IBAction)DeleteAnnotation:(id)sender { [self.mapview removeAnnotation:self.m
-(IBAction)DeleteAnnotation:(id)sender {
[mapview removeAnnotation:[mapview.annotations lastObject]];
}
我甚至试过这样做:
-(IBAction)DeleteAnnotation:(id)sender {
[self.mapview removeAnnotation:self.mapview.annotations.lastObject]];
}
其中mapview
是我的MKMapView
Outlet
两种方法都会遇到的问题是,在删除注释之前,我必须多次按下此特定按钮
此外,注释以一种非常随机的方式删除它们自己
是我做错了什么,还是软件和模拟器的问题?MKMapView的
annotations
属性不能保证以添加注释的相同顺序返回注释
假设annotations
array属性将以添加注释的相同顺序返回注释,这很可能是您看到的“奇怪”行为的原因。有关更多详细信息,请参阅这些相关答案:
要获得您想要的行为(我假设这只是“删除代码显式添加的最后一个注释”),这里有三种可能的方法(可能还有其他方法):
addAnnotation
时更新引用)。如果要删除“上次添加的批注”,请将保存的引用传递到removeAnnotation
。例如:
//in the interface...
@property (nonatomic, strong) id<MKAnnotation> lastAnnotationAdded;
//in the implementation...
//when you add an annotation:
[mapview addAnnotation:someAnnotation];
self.lastAnnotationAdded = someAnnotation; //save the reference
//when you want to remove the "last annotation added":
if (self.lastAnnotationAdded != nil)
{
[mapview removeAnnotation:self.lastAnnotationAdded];
self.lastAnnotationAdded = nil;
}
//在界面中。。。
@属性(非原子,强)id lastAnnotationAdded;
//在执行中。。。
//添加注释时:
[mapview addAnnotation:someAnnotation];
self.lastAnnotationAdded=someAnnotation//保存引用
//当您要删除“最后添加的批注”时:
如果(self.lastAnnotationAdded!=nil)
{
[mapview removeAnnotation:self.lastAnnotationAdded];
self.lastAnnotationAdded=nil;
}
注释数组中循环,并搜索“最后一个”注释(或您感兴趣的任何属性)。一旦对“最后一个”对象(不一定是数组中的最后一个对象)有了引用,就可以对其调用removeAnnotation
。这种方法假设注释对象本身具有某些属性,可以将注释标识为“最后”注释。这可能并不总是可能的
addAnnotation
时将注释对象添加到此数组。这类似于只保留对“添加的最后一个注释”的单个引用,不同的是,您可以按照可以依赖的顺序跟踪整个列表。要删除“最后”一个,您将从数组中获取lastObject
,而不是从地图视图中获取(假设您保持数组的顺序)。在地图上添加/删除注释时,必须确保阵列保持同步