如何判断calloutAcessoryControlTapped中按下了哪个按钮?

时间:2015-04-08 19:54:37

标签: ios mkmapview mkannotation mkannotationview

我使用MapKit,我的针脚有2个标注配件。

我试图实现一个用于更新pin标题的按钮和一个用于删除该pin的按钮。

现在,只要我按下注释上的按钮,它只会删除引脚。

如何让右手按钮与左按钮的响应方式不同?

-(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];
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这一行:

if(view.rightCalloutAccessoryView){

基本上说&#34;如果view.rightCalloutAccessoryView不是nil&#34;。

由于您在 所有 注释视图中设置了右侧附件,因此if条件将 始终 是真的,因此点击 附件将执行if内部的代码,即删除注释。

相反,您要检查在调用委托方法的特定情况下触摸了哪个按钮或控件(而不是视图是否定义了右侧附件)。

幸运的是,委托方法准确传递了在control参数中点击的控件。

control参数可以直接与视图的右/左附件视图进行比较,以判断哪个被点击:

if (control == view.rightCalloutAccessoryView) {

<小时/>
一些不相​​关的观点:

  1. 注释中的latitudelongitude属性属于CLLocationDegrees类型(又名double),其精度高于float,以避免失去准确性,请使用CLLocationDegreesdouble

    CLLocationDegrees lat= annotation.coordinate.latitude;
    
  2. 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];
            }
        }
    }
    
相关问题