2

I created a subclass of MKAnnotationViewwhich when selected display a callout view (similar to the MKPinAnnotationView) which is just a subclass of UIViewwith a button and text for now. 标注被添加到注释视图中。我遇到的问题是我放在标注视图中的按钮从不触发任何动作,它似乎没有响应触摸事件。

我创建一个新的原因MKAnnotationView是因为我需要在注释视图中显示多个文本和两个按钮,而我找不到通过常规MKPinAnnotationView标注实现此目的的方法。

代码:

- (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id ) annotation {
    if(![annotation isKindOfClass:[CSMapAnnotation class]])
        return nil;

    CSMapAnnotation* csAnnotation = (CSMapAnnotation*)annotation;

    CustomAnnotation *customAnnotationView=[[[CustomAnnotation alloc] initWithAnnotation:annotation reuseIdentifier:nil] autorelease];
    MKPinAnnotationView* pin = nil; pin = [[[MKPinAnnotationView alloc] initWithAnnotation:customAnnotationView reuseIdentifier:@"identifier"] autorelease];
    [pin setPinColor: MKPinAnnotationColorRed ];
    MKAnnotationView *annotationView = pin;

    annotationView.canShowCallout = YES;
    [pin setPinColor:(csAnnotation.annotationType == CSMapAnnotationTypeStart) ? MKPinAnnotationColorGreen : ((csAnnotation.annotationType == CSMapAnnotationTypeCarLocation)? MKPinAnnotationColorPurple:MKPinAnnotationColorRed) ];



    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0,0,85,25)];
    [leftView setBackgroundColor:[UIColor clearColor]];

    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setBackgroundImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
    [shareButton setFrame:CGRectMake(19+GAP, 0, 25, 25)];
    [shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:shareButton];


    UIButton *setAlertButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [setAlertButton setBackgroundImage:[UIImage imageNamed:@"alert.png"] forState:UIControlStateNormal];
    [setAlertButton setFrame:CGRectMake(shareButton.frame.origin.x+shareButton.frame.size.width+GAP, 0, 25, 25)];
    [setAlertButton addTarget:self action:@selector(alertButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:setAlertButton];


    annotationView.rightCalloutAccessoryView = leftView;
    [leftView release];

    return annotationView;
}

-(void)shareButtonAction:(id)sender {
   NSLog(@"%s",_cmd);
}

当我单击 shareButton 时,未调用 shareButtonAction 操作...


我也检查了上面的委托,但是当安装到 iPhone 3.0 时它没有被调用。如果我只有一个按钮来右标注,这个委托将调用,但是(在上述情况下)它在添加带有两个按钮的视图时不会调用。它发生在 iPhone 3.0 中。

4

1 回答 1

1

我不知道您是否知道(或者您是否关心),但是您正在将 MKAnnotationView 传递给要求 MKAnnotation 的方法,这势必会导致您以后遇到问题。

也正因为如此,我不知道我的答案是否真的适合你,但是当你点击标注的附件控件时,有一个委托方法会被调用。将自己设置为 mapview 实例委托后,只需实现:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
   NSLog (@"Callout accessory control tapped");
}
于 2011-02-18T10:11:57.397 回答