Search code examples
objective-candroid-mapviewmapkitmkannotationdisclosure

How can i add a disclosure button to a MKAnnotation?


I want to add a disclosure button to a MKAnnotation to segue to another view.

The button should look like this one:

Image

Here's my .h and .m files.


.h file

//
//  POI.h
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface POI : NSObject <MKAnnotation> {

    NSString *title;
    NSString *subtitle;
    CLLocationCoordinate2D coordinate;
}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

- (id)initWithCoordinate:(CLLocationCoordinate2D)_coordinate title:(NSString *)_titolo andSubTitle:(NSString *)_sottotitolo;


@end

.m file

//
//  POI.m

#import "POI.h"



@implementation POI

@synthesize title, subtitle, coordinate;
-(id)initWithCoordinate:(CLLocationCoordinate2D)_coordinate title:(NSString *)_titolo andSubTitle:(NSString *)_sottotitolo {

    [self setTitle:_titolo];
    [self setSubtitle:_sottotitolo];
    [self setCoordinate:_coordinate];



    return self;
}

@end

in my ViewController i call this using:

  pinLocation.latitude = 4.8874;
    pinLocation.longitude = 1.400;
    POI *poi = [[POI alloc] initWithCoordinate:pinLocation title:@"foo" andSubTitle:@"bar"];
    [_mapView addAnnotation:poi];

Solution

  • Three steps.

    1) In your header file (.h) or your implementation file's (.m) class extension conform to MKMapViewDelegate:

    @interface ViewController : UIViewController <MKMapViewDelegate> { ... } 
    

    2) Set your view controller as the delegate of MKMapViewDelegate to receive delegate callbacks. Commonly done in viewDidLoad:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        self.mapView.delegate = self;
    }
    

    3) Implement the following delegate function to show the disclosure button:

    - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
    {   
        MKPinAnnotationView *newAnnotation = [[MKPinAnnotationView alloc]     initWithAnnotation:annotation reuseIdentifier:@"pinLocation"];
    
        newAnnotation.canShowCallout = YES;
        newAnnotation.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
        return newAnnotation;
    }
    

    the following function will assist in determining what action (in your case, presenting a view) is taken upon touching the disclosure button.

    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
    {
        //launch a new view upon touching the disclosure indicator
        TestVCViewController *tvc = [[TestVCViewController alloc] initWithNibName:@"TestVCViewController" bundle:nil];
        [self presentViewController:tvc animated:YES completion:nil];
    }