Replace icon pin by text label in annotation?

拈花ヽ惹草 提交于 2019-11-27 14:21:34

Yes, it's possible.

In iOS MapKit, you'll need to implement the viewForAnnotation delegate method and return an MKAnnotationView with a UILabel added to it.

For example:

-(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;
}

Make sure the map view's delegate property is set otherwise this delegate method will not get called and you will get the default red pins instead.

Barry Langdon-Lassagne

Here's a Swift 3 variation of the delegate method mentioned in Anna's comment above. Make sure your class conforms to MKMapViewDelegate and that the mapView's delegate is set to self in viewDidLoad().

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let reuseId = "reuseid"
    var av = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
    if av == nil {
        av = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
        lbl.backgroundColor = .black
        lbl.textColor = .white
        lbl.alpha = 0.5
        lbl.tag = 42
        av?.addSubview(lbl)
        av?.canShowCallout = true
        av?.frame = lbl.frame
    }
    else {
        av?.annotation = annotation
    }

    let lbl = av?.viewWithTag(42) as! UILabel
    lbl.text = annotation.title!

    return av
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!