2012-03-22 11 views

risposta

30

Sì, è possibile.

In iOS MapKit, è necessario implementare il metodo delegato viewForAnnotation e restituire un MKAnnotationView con un UILabel aggiunto.

Ad esempio:

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

Assicurarsi proprietà delegate della vista mappa è impostata altrimenti questo metodo delegato non verrà chiamato e si otterrà il predefinite spilli rossi, invece.

+0

Grazie mille per la risposta veloce. Presto testerò questo codice. A presto. – joumerlin

+0

Funzionante bene, thx ... – joumerlin

2

Ecco una variazione di Swift 3 del metodo delegato menzionato nel commento di Anna sopra. Assicurati che la tua classe sia conforme a MKMapViewDelegate e che il delegato di mapView sia impostato su self in 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 
} 
Problemi correlati