我正在使用 MapKit,我的图钉中有 2 个标注配件。
我正在尝试实现一个用于更新图钉标题的按钮和一个用于删除图钉的按钮。
现在,只要我按下注释上的按钮,它只会删除图钉。
如何让它对右键和左键做出不同的响应?
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
id <MKAnnotation> annotation = [view annotation];
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
NSLog(@"Clicked");
if(view.rightCalloutAccessoryView){
[self.mapView removeAnnotation:annotation];
}
else{
float lat= annotation.coordinate.latitude;
float longitude = annotation.coordinate.longitude;
[self.mapView removeAnnotation:annotation];
MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc] init];
pointAnnotation.title = _titleOut.text;
pointAnnotation.subtitle = _subtitle.text;
pointAnnotation.coordinate = CLLocationCoordinate2DMake(lat, longitude);
[self.mapView addAnnotation:pointAnnotation];
}
}
}
最佳答案
这一行:
if(view.rightCalloutAccessoryView){
本质上说“如果 view.rightCalloutAccessoryView 不为零”。
由于您要在所有 注释 View 上设置右侧附件,因此 if
条件将始终为真,因此点击任一个附件将执行 if
中的代码也就是去掉注解。
相反,您想检查在调用委托(delegate)方法的这种特定情况下点击了哪个按钮或控件(而不是 View 是否定义了右侧附件)。
幸运的是,委托(delegate)方法准确传递了在 control
中点击的控件。范围。
control
参数可以直接与 View 的右/左附件 View 进行比较,以判断哪个被点击:
if (control == view.rightCalloutAccessoryView) {
一些不相关的点:
latitude
和longitude
注释中的属性属于CLLocationDegrees
类型(又名double
)比float
具有更高的精度所以为了避免失去准确性,请使用CLLocationDegrees
或double
:CLLocationDegrees lat= annotation.coordinate.latitude;
MKPointAnnotation
允许您更改title
直接(它不像默认的id<MKAnnotation>
那样是只读的)所以您不需要删除和创建新的注释。它稍微简化了代码:-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control { if ([view.annotation isKindOfClass:[MKPointAnnotation class]]) { NSLog(@"Clicked"); if (control == view.rightCalloutAccessoryView) { [self.mapView removeAnnotation:view.annotation]; } else { // Cast view.annotation as an MKPointAnnotation // (which we know it is) so that compiler sees // title is read-write instead of the // default id<MKAnnotation> which is read-only. MKPointAnnotation *pa = (MKPointAnnotation *)view.annotation; pa.title = _titleOut.text; pa.subtitle = _subtitle.text; //If you want callout to be closed automatically after //title is changed, uncomment the line below: //[mapView deselectAnnotation:pa animated:YES]; } } }
关于ios - 如何判断在 calloutAcessoryControlTapped 中按下了哪个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524170/