2012-03-22 9 views
17

¿Es posible reemplazar el icono de una anotación por una etiqueta de texto dinámico?Reemplazar el pin de icono por etiqueta de texto en la anotación?

¿Tal vez usar css o crear dinámicamente una imagen?

Por ejemplo, una etiqueta se hace con CSS en Google Maps API con JavaScript.

+0

Hola, intenta elaborar un poco más. Puede algún código de lo que ha intentado. –

Respuesta

30

Sí, es posible.

En iOS MapKit, deberá implementar el método de delegado viewForAnnotation y devolver un MKAnnotationView con un UILabel añadido.

Por ejemplo:

-(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; 
} 

Asegúrese de que la propiedad de la vista del mapa delegate se establece de otro modo no se llamará este método delegado y obtendrá alfileres rojos del defecto en su lugar.

+0

Muchas gracias por la respuesta rápida. Pronto probaré este código. Te veo pronto. – joumerlin

+0

trabajando bien, thx ... – joumerlin

2

Aquí hay una variación de Swift 3 del método delegado mencionado en el comentario anterior de Anna. Asegúrese de que su clase se ajuste a MKMapViewDelegate y que el delegado de mapView esté configurado en self en viewDidLoad().

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 
} 
Cuestiones relacionadas