MKMapView:自定义视图代替 Annotation Pin [英] MKMapView: Instead of Annotation Pin, a custom view

查看:362
本文介绍了MKMapView:自定义视图代替 Annotation Pin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want to display an image in my MKMapView instead of little rock pin.

Can someone please put some helpful code here, or tell the way how to do it?

-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
    (id <MKAnnotation>)annotation {
    MKPinAnnotationView *pinView = nil; 
    if(annotation != mapView.userLocation) 
    {
        static NSString *defaultPinID = @"com.invasivecode.pin";
        pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinView == nil ) pinView = [[MKPinAnnotationView alloc]
                                          initWithAnnotation:annotation reuseIdentifier:defaultPinID];

        pinView.pinColor = MKPinAnnotationColorGreen; 
        pinView.canShowCallout = YES;
        pinView.animatesDrop = YES;
        pinView.image = [UIImage imageNamed:@"pinks.jpg"]; //as suggested by Squatch
    } 
    else {
        [mapView.userLocation setTitle:@"I am here"];
    }
    return pinView;
}

I am expecting my image pinks.jpg to be on the map, pinning the location instead of default pin view (rock pin shaped). But still I am getting the default image of the pin.

解决方案

When you want to use your own image for an annotation view, you should create an MKAnnotationView instead of an MKPinAnnotationView.

MKPinAnnotationView is a subclass of MKAnnotationView so it has an image property but it generally overrides that and draws a pin image (that's what it's for).

So change the code to:

-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation 
{
    MKAnnotationView *pinView = nil; 
    if(annotation != mapView.userLocation) 
    {
        static NSString *defaultPinID = @"com.invasivecode.pin";
        pinView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinView == nil ) 
            pinView = [[MKAnnotationView alloc]
                                         initWithAnnotation:annotation reuseIdentifier:defaultPinID];

        //pinView.pinColor = MKPinAnnotationColorGreen; 
        pinView.canShowCallout = YES;
        //pinView.animatesDrop = YES;
        pinView.image = [UIImage imageNamed:@"pinks.jpg"];    //as suggested by Squatch
    } 
    else {
        [mapView.userLocation setTitle:@"I am here"];
    }
    return pinView;
}


Notice that animatesDrop is also commented out since that property only exists in MKPinAnnotationView.

If you still want your image annotations to drop, you'll have to do the animation yourself. You can search Stack Overflow for "animatesdrop mkannotationview" and you'll find several answers. Here are the first two:

这篇关于MKMapView:自定义视图代替 Annotation Pin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆