2011-09-18 72 views
10

我創建了一個註解,我將其添加到MKMapView中。我將如何去有一個自定義的圖像,而不是標準的紅色別針?MKAnnotation的自定義圖像

@interface AddressAnnotation : NSObject<MKAnnotation> { 
    CLLocationCoordinate2D coordinate; 
    NSString *title; 
    NSString *subtitle; 
    MKPinAnnotationColor pinColor; 
} 
@property (nonatomic,retain) NSString *title; 
@property (nonatomic,retain) NSString *subtitle; 
@property (nonatomic, assign) MKPinAnnotationColor pinColor; 
@end 

回答

1

覆蓋mapView:viewForAnnotation:委託方法。如果annotation參數指向您的一個自定義註釋,則返回一個看起來符合您的喜好的自定義視圖。

+0

你能指點我一個如何做到這一點的例子嗎?我是客觀的新手。謝謝 – 3sl

18

的MKMapView從其委託方法mapView:viewForAnnotation:獲取其銷意見所以,你必須:

  1. 設置您的視圖控制器作爲地圖的委託。
  2. 實現mapView:viewForAnnotation:在你的控制器中。

設置你的控制器作爲代表

@interface MapViewController : UIViewController <MKMapViewDelegate> 

馬克與委託協議的接口。這讓我們在Interface Builder(IB)中將控制器設置爲MKMapView的委託。打開包含地圖的.xib文件,右鍵單擊MKMapView,然後將delegate插座拖到控制器。
如果您更願意使用代碼IB,請在控制器的viewDidLoad方法中添加self.yourMapView.delegate=self;。結果將是相同的。

實現的MapView:viewForAnnotation:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    // this part is boilerplate code used to create or reuse a pin annotation 
    static NSString *viewId = @"MKPinAnnotationView"; 
    MKPinAnnotationView *annotationView = (MKPinAnnotationView*) 
     [self.mapView dequeueReusableAnnotationViewWithIdentifier:viewId]; 
    if (annotationView == nil) { 
     annotationView = [[[MKPinAnnotationView alloc] 
      initWithAnnotation:annotation reuseIdentifier:viewId] autorelease]; 
    } 
    // set your custom image 
    annotationView.image = [UIImage imageNamed:@"emoji-ghost.png"]; 
    return annotationView; 
} 
0

要設置自定義圖像,而不是非標準MKPinAnnotationView這樣做是使用MKAnnotationView與功能- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation的唯一途徑。舉例如下:

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

    if ([annotation isKindOfClass:[MKUserLocation class]]) { 
       return nil; 
    } 

    static NSString *identifier = @"Annotation"; 

    MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; 

    if (!aView) { 
      aView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; 
      aView.image = [UIImage imageNamed:@"Untitled1.png"]; 
      aView.canShowCallout = YES; 
      aView.draggable = YES; 
    } else { 
      aView.annotation = annotation; 
    } 

    return pin; 
} 

對於aView.image值您可以設置自己的圖像。並且還要查看MKAnnotationView類引用以更好地處理它。