如何向MKAnnotation添加公开按钮?

时间:2012-12-26 22:22:36

标签: objective-c android-mapview mapkit mkannotation disclosure

我想向MKAnnotation添加一个公开按钮以转到另一个视图。

按钮应如下所示:

Image

这是我的 .h .m 文件。


.h文件

//
//  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文件

//
//  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

在我的ViewController中我使用:

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

2 个答案:

答案 0 :(得分:12)

三个步骤。

1)在头文件(.h)中,您的实现文件(.m)类扩展符合MKMapViewDelegate

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

2)将视图控制器设置为MKMapViewDelegate的委托,以接收委托回调。通常在viewDidLoad中完成:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.mapView.delegate = self;
}

3)实现以下委托功能以显示披露按钮:

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

以下功能将有助于确定在触摸公开按钮时采取的操作(在您的情况下,呈现视图)。

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

答案 1 :(得分:0)

在您的- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation方法中使用此:

annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

其中annotationView是要返回的视图。