2012-03-22 122 views
17

是否可以用動態文本標籤替換註釋的圖釘圖標?用註釋中的文本標籤替換圖標引腳?

也許使用css或動態創建圖像?

例如,使用JavaScript在Google Maps API上使用CSS完成標籤。

+0

你好,試着再詳細一點。可以嘗試一些代碼。 – 2012-03-22 13:13:35

回答

30

是的,這是可能的。

在iOS MapKit中,您需要實施viewForAnnotation委託方法,並返回MKAnnotationView並添加UILabel

例如:

-(MKAnnotationView *)mapView:(MKMapView *)mapView 
    viewForAnnotation:(id<MKAnnotation>)annotation 
{ 
    if ([annotation isKindOfClass:[MKUserLocation class]]) 
     return nil; 

    static NSString *reuseId = @"reuseid"; 
    MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId]; 
    if (av == nil) 
    { 
     av = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId] autorelease]; 

     UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease]; 
     lbl.backgroundColor = [UIColor blackColor]; 
     lbl.textColor = [UIColor whiteColor]; 
     lbl.alpha = 0.5; 
     lbl.tag = 42; 
     [av addSubview:lbl]; 

     //Following lets the callout still work if you tap on the label... 
     av.canShowCallout = YES; 
     av.frame = lbl.frame; 
    } 
    else 
    { 
     av.annotation = annotation; 
    } 

    UILabel *lbl = (UILabel *)[av viewWithTag:42]; 
    lbl.text = annotation.title;   

    return av; 
} 

確保地圖視圖的delegate屬性的設置,否則此委託方法將不會被調用,你會得到默認的紅色圖釘來代替。

+0

非常感謝您的快速響應。我會很快測試這個代碼。再見。 – joumerlin 2012-03-22 17:55:35

+0

正常工作,thx ... – joumerlin 2012-03-24 16:21:54

2

下面是Anna上面評論中提到的代理方法的Swift 3變體。確保你的類符合MKMapViewDelegate,並且mapView的委託在viewDidLoad()中設置爲self。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    if annotation is MKUserLocation { 
     return nil 
    } 

    let reuseId = "reuseid" 
    var av = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) 
    if av == nil { 
     av = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 30)) 
     lbl.backgroundColor = .black 
     lbl.textColor = .white 
     lbl.alpha = 0.5 
     lbl.tag = 42 
     av?.addSubview(lbl) 
     av?.canShowCallout = true 
     av?.frame = lbl.frame 
    } 
    else { 
     av?.annotation = annotation 
    } 

    let lbl = av?.viewWithTag(42) as! UILabel 
    lbl.text = annotation.title! 

    return av 
}