在注释中用文本标签替换图标引脚?

jou*_*lin 18 iphone mapkit ios

是否可以用动态文本标签替换注释的图钉图标?

也许使用CSS,或动态创建图像?

例如,使用JavaScript在Google Maps API上使用CSS完成标签.

小智 31

是的,这是可能的.

在iOS中MapKit,你需要实现的viewForAnnotation委托方法,并返回一个MKAnnotationView具有UILabel添加到它.

例如:

-(MKAnnotationView *)mapView:(MKMapView *)mapView 
    viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;

    static NSString *reuseId = @"reuseid";
    MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (av == nil)
    {
        av = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId] autorelease];

        UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease];
        lbl.backgroundColor = [UIColor blackColor];
        lbl.textColor = [UIColor whiteColor];
        lbl.alpha = 0.5;
        lbl.tag = 42;
        [av addSubview:lbl];

        //Following lets the callout still work if you tap on the label...
        av.canShowCallout = YES;
        av.frame = lbl.frame;
    }
    else
    {
        av.annotation = annotation;
    }

    UILabel *lbl = (UILabel *)[av viewWithTag:42];
    lbl.text = annotation.title;        

    return av;
}
Run Code Online (Sandbox Code Playgroud)

确保设置了地图视图的delegate属性,否则将不会调用此委托方法,您将获得默认的红色引脚.