rightCalloutAccessoryView在MKPinAnnotationView上未显示

4

我在MKMapView上使用MKPinAnnotationView,标题和副标题正常显示,但是rightCalloutAccessoryView没有显示。

我尝试了很多谷歌搜索,但还没有解决。我的代码如下:

- (void)addAnnotation
{
    CLLocationCoordinate2D theCoordinate = self.location.coordinate;

    MapAnnotation *annotation = [[MapAnnotation alloc] initWithCoordinate:theCoordinate];
    annotation.title = @"Pin";
    annotation.subtitle = @"More information";

    [self.mapView addAnnotation:annotation];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MapAnnotation class]]) {
        static NSString *reuseIdentifier = @"MyMKPinAnnotationView";
        MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];

        if (!annotationView) {
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
            annotationView.pinColor = MKPinAnnotationColorRed;
            annotationView.enabled = YES;
            annotationView.canShowCallout = YES;
            annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        } else {
            annotationView.annotation = annotation;
        }
    }

    return nil;
}

请注意可以显示标题和副标题。
提前致谢。

3
你的viewForAnnotation没有返回annotationView。所以请确保返回它(如果返回nil,默认行为将会发生,而不管你所做的一切)。请参考我的修改后答案。 - Rob
1个回答

7

默认情况下,注释视图会显示标题和副标题。如果您想执行其他操作(例如 rightCalloutAccessorView),则必须确保通过设置 MKMapViewdelegate 并确保您的 viewForAnnotation 返回您正在创建的 annotationView 来调用 viewForAnnotation

可能出现以下两个问题之一:

  1. Your viewForAnnotation is returning nil in all cases. Make sure you you return annotationView after creating/modifying it.

  2. If your map view's delegate hasn't been set, your current viewForAnnotation would not be called at all.

    Make sure you have set the delegate. You can do this programmatically:

    self.mapView.delegate = self;
    

    Or you can do this in IB (by selecting the connections inspector, the rightmost tab of the right panel and control-drag from the delegate to the status bar of the scene):

    enter image description here

    If this is the case, if you put a NSLog statement or breakpoint in your viewForAnnotation. You might not see it being called at all if the delegate hasn't been set up properly.


1
谢谢!天哪...昨晚我很困。 - Jason Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接