Displaying Pin with Title (annotation) once map loads

后端 未结 2 506
无人及你
无人及你 2021-01-02 16:23

I am working on my first app and within it I\'m just trying to have on button click show a map with a pin (and title on this pin of location). I was able to load the mapview

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 16:52

    For that you need to create annotation create one class which has CLLocationCoordinate2D,title,subtitle like this .h file

    #import 
    #import 
    
    
    @interface DisplayMap : NSObject  {
    
        CLLocationCoordinate2D coordinate; 
        NSString *title; 
        NSString *subtitle;
    }
    @property (nonatomic, assign) CLLocationCoordinate2D coordinate; 
    @property (nonatomic, copy) NSString *title; 
    @property (nonatomic, copy) NSString *subtitle;
    
    @end
    

    and .m file

    #import "DisplayMap.h"
    
    
    @implementation DisplayMap
    
    @synthesize coordinate,title,subtitle;
    
    
    -(void)dealloc{
        [title release];
        [super dealloc];
    }
    
    @end
    

    and then add following code to viewdidload

    DisplayMap *ann = [[DisplayMap alloc] init]; 
    ann.title=@"put title here";
    ann.coordinate = region.center; 
    [mapView addAnnotation:ann];
    

    and implement following method

    -(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
    (id )annotation {
        MKPinAnnotationView *pinView = nil; 
        if(annotation != mapView.userLocation) 
        {
            static NSString *defaultPinID = @"com.invasivecode.pin";
            pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
            if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
                                              initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
    
            pinView.pinColor = MKPinAnnotationColorPurple; 
            pinView.canShowCallout = YES;
            pinView.animatesDrop = YES;
        } 
        else {
            [mapView.userLocation setTitle:@"I am here"];
        }
        return pinView;
    }
    

    Follow this tutorial:code with explanation is given:

提交回复
热议问题