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

时间:2012-03-22 12:58:08

标签: iphone ios mapkit

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

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

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

2 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分:2)

以上是Anna上述评论中提到的委托方法的Swift 3变体。确保您的类符合MKMapViewDelegate,并且mapView的委托在viewDidLoad()中设置为self。

val s = UserService.create<String>()