Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

iphone - Replace icon pin by text label in annotation?

Is it possible to replace the pin icon of an annotation by a dynamic text label?

Maybe using css, or dynamically creating an image?

For example a label is done with CSS on Google Maps API with JavaScript.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...