2014-05-10 82 views
0

我想將圖像設置爲MKAnnotationView。
但圖像沒有反映出來。這是正常的紅色針腳。
MKAnnotationView.image不反映

ViewController.m

#import <UIKit/UIKit.h> 
#import <MapKit/MapKit.h> 
#import <CoreLocation/CoreLocation.h> 
#import "CustomAnnotation.h" 
@interface ViewController()<MKMapViewDelegate> 
@end 
@implementation ViewController{ 
    MKMapView* _mapView; 
} 

- (void)viewDidLoad{ 
    CustomAnnotation* annotation = [[CustomAnnotation alloc]init]; 
    annotation.coordinate = CLLocationCoordinate2DMake(35.6699877, 139.7000456); 
    annotation.image = [UIImage imageNamed:@"annotation.png"]; 
    [_mapView addAnnotations:@[annotation]]; 
} 

CustomAnnotation.h

#import <UIKit/UIKit.h> 
#import <MapKit/MapKit.h> 
#import <CoreLocation/CoreLocation.h> 

@interface CustomAnnotation : MKAnnotationView 
@property (readwrite, nonatomic) CLLocationCoordinate2D coordinate; 
@property (readwrite, nonatomic, strong) NSString* title; 
@end 

CustomAnnotation.m

#import "CustomAnnotation.h" 
@implementation CustomAnnotation 
@end 

回答

1

要使用自定義圖像,你已經創建並返回一個MKAnnotationView地圖視圖的viewForAnnotation代表方法。

如果您沒有實現該委託方法,則地圖視圖將爲您添加的註釋顯示默認的紅色別針(不管註釋是什麼類別)。

這裏是你如何能實現它的一個例子:

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation 
{ 
    if (! [annotation isKindOfClass:[CustomAnnotation class]]) 
    { 
     //if this annotation is not a CustomAnnotation 
     //(eg. user location blue dot), 
     //return nil so the map view draws its default view for it... 
     return nil; 
    } 

    static NSString *reuseId = @"ann"; 
    MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId]; 
    if (av == nil) 
    { 
     av = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId]; 
     av.canShowCallout = YES; 
     av.image = [UIImage imageNamed:@"annotation.png"]; 
    } 
    else 
    { 
     av.annotation = annotation; 
    } 

    return av; 
} 

一定要設置地圖視圖的delegate財產無論是在代碼或情節提要/廈門國際銀行連接的插座。如果沒有設置delegate,即使您已經實施了該方法,地圖視圖也不會調用viewForAnnotation方法,並且您仍將獲得默認的紅色針腳。


addAnnotationaddAnnotations方法僅要求用於註解模型對象(即實現MKAnnotation協議,它主要由coordinate屬性的對象)。

視圖那些註釋模型對象必須在viewForAnnotation委託方法返回。

即使你CustomAnnotation類沒有明確聲明它符合MKAnnotation,它實現了一個coordinate屬性,所以在地圖視圖能夠顯示在地圖上。

它碰巧也是MKAnnotationView的子類的事實是地圖視圖不關心或使用註釋模型對象的東西。

您的註記模型對象不應該是MKAnnotationView的子類,因爲它只會導致混淆。它應該只執行MKAnnotation協議,因此它應該是NSObject<MKAnnotation>(或除NSObject之外的其他一些自定義類)的子類。

更改CustomAnnotation接口:

@interface CustomAnnotation : NSObject<MKAnnotation> 

變化從strongcopytitle屬性來匹配MKAnnotation協議:

@property (readwrite, nonatomic, copy) NSString* title; 

由於CustomAnnotation不再是一個MKAnnotationView,取出image =線從viewDidLoad,一定要設置註釋的title其他當您點擊它時,標註不會顯示:

//annotation.image = [UIImage imageNamed:@"annotation.png"]; 
annotation.title = @"annotation";