2014-06-15 155 views
3

我想在我的MKAnnotationView上使用下面的代碼時使用自定義圖像我的註釋中沒有圖像。我檢查了調試以確保圖像正確地加載到UIImageMKAnnotationView自定義按鈕圖像

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


    MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"String"]; 
    if(!annotationView) { 

     annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"String"]; 
     UIButton *directionButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"]; 

     [directionButton setImage:directionIcon forState:UIControlStateNormal]; 

     annotationView.rightCalloutAccessoryView = directionButton; 
    } 

    annotationView.enabled = YES; 
    annotationView.canShowCallout = YES; 

    return annotationView; 
} 

回答

0

爲了顯示標註,必須選擇標註。要以編程方式做到這一點,請致電:

[mapView selectAnnotation:annotation animated:YES]; 

其中annotation是您要顯示的標註具體MKAnnotation

你幾乎可以肯定要把它放在- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views

,需要考慮幾個注意事項,所以這裏有一些偉大的答案和相關討論其他兩個職位:

7

有兩個主要問題:

  1. frame自定義標註按鈕未設置,使其基本不可見。
  2. 正在創建MKAnnotationView,但其image屬性(註釋本身的圖像 - 不是標註按鈕的)未設置。這使整個註釋不可見。

對於問題1,將按鈕的框架設置爲適當的值。例如:

UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"]; 
directionButton.frame = 
    CGRectMake(0, 0, directionIcon.size.width, directionIcon.size.height); 

對於問題2,設置註釋視圖的image(或創建一個MKPinAnnotationView代替):

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


另外,你應該通過更新annotation正確處理視圖再利用屬性。
完整示例:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
{  
    MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"String"]; 
    if(!annotationView) { 

     annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"String"]; 

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

     UIButton *directionButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"]; 
     directionButton.frame = 
      CGRectMake(0, 0, directionIcon.size.width, directionIcon.size.height); 

     [directionButton setImage:directionIcon forState:UIControlStateNormal]; 

     annotationView.rightCalloutAccessoryView = directionButton; 
     annotationView.enabled = YES; 
     annotationView.canShowCallout = YES; 
    } 
    else { 
     //update annotation to current if re-using a view 
     annotationView.annotation = annotation; 
    }  

    return annotationView; 
}