标准的 UI 方法是使用标注视图并添加一个附件按钮,如 progrmr 所示。
但是,如果您必须将按钮直接添加到MKAnnotationView,您的方法的问题是MKPinAnnotationView 的默认框架(不能轻易更改)小于您的按钮添加因此大多数按钮将不会响应触摸,即使您切换到使用 MKAnnotationView 并增加帧大小,MKMapView 也会阻止按钮获得任何触摸。
您需要做的是向按钮添加UITapGestureRecognizer(使用手势处理程序的操作方法而不是按钮上的addTarget)并将按钮添加到具有适当帧大小的普通MKAnnotationView MKPinAnnotationView.
例子:
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id<MKAnnotation>)annotation
{
MKAnnotationView *annView = (MKAnnotationView *)[mapView
dequeueReusableAnnotationViewWithIdentifier: @"pin"];
if (annView == nil)
{
annView = [[[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:@"pin"] autorelease];
annView.frame = CGRectMake(0, 0, 200, 50);
UIButton *pinButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
pinButton.frame = CGRectMake(0, 0, 140, 28);
pinButton.tag = 10;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handlePinButtonTap:)];
tap.numberOfTapsRequired = 1;
[pinButton addGestureRecognizer:tap];
[tap release];
[annView addSubview:pinButton];
}
annView.annotation = annotation;
UIButton *pb = (UIButton *)[annView viewWithTag:10];
[pb setTitle:annotation.title forState:UIControlStateNormal];
return annView;
}
- (void) handlePinButtonTap:(UITapGestureRecognizer *)gestureRecognizer
{
UIButton *btn = (UIButton *) gestureRecognizer.view;
MKAnnotationView *av = (MKAnnotationView *)[btn superview];
id<MKAnnotation> ann = av.annotation;
NSLog(@"handlePinButtonTap: ann.title=%@", ann.title);
}
请注意,这将阻止地图视图的 didSelectAnnotationView 委托方法触发。如果您需要触发该方法(在 addition 到按钮的手势处理程序方法中),请添加以下内容:
//in the view controller's interface:
@interface YourVC : UIViewController <UIGestureRecognizerDelegate>
//where the UITapGestureRecognizer is created:
tap.delegate = self;
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer
:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}