ios - MKMapView:自定义 View 代替 Annotation Pin

我想在我的 MKMapView 中显示一个图像,而不是小 rock pin

有人可以在这里放一些有用的代码,或者告诉怎么做吗?

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

我希望我的图像 pinks.jpg 出现在 map 上,固定位置而不是默认的图钉 View (摇滚别针形状)。但我仍然得到了 pin 的默认图像。

最佳答案

当您想将自己的图像用于注释 View 时,您应该创建一个 MKAnnotationView 而不是 MKPinAnnotationView

MKPinAnnotationViewMKAnnotationView 的子类,因此它具有 image 属性,但它通常会覆盖该属性并绘制图钉图像(就是这样为)。

所以把代码改成:

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


请注意,animatesDrop 也被注释掉了,因为该属性只存在于 MKPinAnnotationView 中。

如果您仍希望删除图像注释,则必须自己制作动画。您可以在 Stack Overflow 中搜索“animatesdrop mkannotationview”,您会找到几个答案。这是前两个:

  • Is it possible to call animatesDrop in a MKAnnotationView rather than MKPinAnnotationView?
  • How can I create a custom "pin-drop" animation using MKAnnotationView?

https://stackoverflow.com/questions/9814988/

相关文章:

objective-c - objective-c : convert a NSMutableStr

c++ - 我可以在同一个 Xcode 项目中拥有 Swift、Objective-C、C 和 C+

iPhone - dequeueReusableCellWithIdentifier 用法

objective-c - Objective-C 中 typeof、__typeof 和 __ty

ios - 如何为 iOS 构建 Unity3d 插件

objective-c - 将自定义 subview (在 xib 中创建)添加到 View Con

objective-c - 如何在没有死锁的情况下同步调度主队列?

iphone - NSNumber 和 NSInteger 有什么区别?

objective-c - 将参数传递给由 NSTimer 调用的方法

") 运算符在 C 与 Objec">objective-c - 点 (".") 运算符和箭头 ("->") 运算符在 C 与 Objec