ios - 如何在 MKMapView 的 MKAnnotation 上设置图像

标签 ios iphone

我正在开发一个聊天应用程序,我必须在 map 上显示所有 friend 的图像。 请提供实现指南。

我使用了以下代码...

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
 {

MKPinAnnotationView *annView = [[MKPinAnnotationView alloc]init]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Done.png"]];

annView.animatesDrop = TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
[annView addSubview:imageView];
return annView;
 }

谢谢

最佳答案

enter image description here

你做错的是你返回了类 MKPinAnnotationView 的对象,它用于显示 pin-annotation。

您应该使用 MKAnnotationView 类的对象。然后,通过更改其图像对其进行自定义:

annotationView.image = [UIImage imageNamed:@"friend_image.png"];

现在,您可以获得 friend 的照片,而不是默认的 pin 图片。

下面是解决您问题的完整代码:

  - (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
    {
        static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier";

        MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier];

        if (annotationView == nil)
        {
            annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier] autorelease];
        }

        // here you can assign your friend's image    
        annotationView.image = [UIImage imageNamed:@"friend_image.png"];
        annotationView.annotation = annotation;

        // add below line of code to enable selection on annotation view
        annotationView.canShowCallout = YES

        return annotationView;
    }

关于ios - 如何在 MKMapView 的 MKAnnotation 上设置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24527912/

相关文章:

iphone - 基本的 iPhone 计时器示例

ios - UICollectionView 中滚动或重新加载数据时出现内存泄漏问题

ios - 在 macOS Sierra 10.12 上运行 Xcode 6.x

ios - TableView 的 cellForRowAtIndexPath : not being called

iphone - 横向模式下的 UIAlertView

ios - 当主视图 Controller 是 UITabBarController 时,自适应显示细节 segue 转换为模态而不是在 iPhone 上推送

iphone - Xcode > 产品 > 存档,协同设计问题

ios - 谷歌分析时间未显示

ios - Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域=NSCocoaErrorDomain 代码=3840

iphone - 什么是 _CDSnapshot_EntityName?