How to set image on MKAnnotation in MKMapView

前端 未结 5 800
盖世英雄少女心
盖世英雄少女心 2021-01-06 23:53

I am developing an app for chating, I have to display all friends on a Map with their image. Please provide guidance to implement it.

I have used following code...

5条回答
  •  庸人自扰
    2021-01-07 00:20

    enter image description here

    I have already posted one answer with different style annotation. But, if you want shown annotation as in above image, you have to use leftCalloutAccessoryView property of MKAnnotationView class as below:

    -> First, create pinAnnotation and add it to mapView in viewDidLoad or where you created mapView:

        // Add the annotation to our map view
        MKPointAnnotation * pointAnnotation = [[MKPointAnnotation alloc] init];
        pointAnnotation.title = @"Rakesh Thummar";
        pointAnnotation.subtitle = @"Ahmedabad";
        pointAnnotation.coordinate = coord;
        [mapView addAnnotation:pointAnnotation];
    

    -> Then, use leftCalloutAccessoryView property of MKAnnotationView class:

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation
    {
        static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier";
    
        MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier];
    
        if (annotationView == nil) {
    
            // if you want to show pinPoint create object of MKPinAnnotationView class instead of MKAnnotationView class
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier];
        }
    
        annotationView.canShowCallout = YES;
    
        // Add a custom image to the left side of the callout.
        UIImageView *myCustomImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo1_40.png"]];
        annotationView.leftCalloutAccessoryView = myCustomImage;
    
        return annotationView;
    }
    

提交回复
热议问题