通过MKAnnotation CalloutAccessoryControlTapped传递自定义属性

时间:2013-02-13 10:51:27

标签: ios objective-c mkmapview mapkit mkannotation

我正在尝试执行通过MKAnnotation传递自定义属性(placeId)的简单功能。我已经使用名为“MapViewAnnotation”的自定义类设置了所有内容。

当用户激活CalloutAccessoryControlTapped时,我想简单地将一个额外的值从MapViewController传递给DetailViewController。我可以使标题/副标题起作用,但我需要修改我的代码以允许自定义变量。

我已经尝试了一段时间,无法让它正常工作。任何帮助都会很棒!谢谢!

MapViewAnnotation.h

@interface MapViewAnnotation : NSObject <MKAnnotation> {
    NSString *title;
    CLLocationCoordinate2D coordinate;
}

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

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d;

@end

MapViewAnnotation.m

@implementation MapViewAnnotation

@synthesize title, coordinate, subtitle;

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d {
    title = ttl;
    coordinate = c2d;
    subtitle = @"Test Subtitle";
    return self;
}

@end

MapViewController.m中的注释创建 - 在这里你可以看到我正在使用副标题来传递placeId(底线)

location.latitude = [dictionary[@"placeLatitude"] doubleValue];
location.longitude = [dictionary[@"placeLongitude"] doubleValue];    

newAnnotation = [[MapViewAnnotation alloc] initWithTitle:dictionary[@"placeName"]
                                               andCoordinate:location];

newAnnotation.subtitle = dictionary[@"placeId"];

CalloutAccessoryControlTapped在MapViewController.m - 在这里你可以看到我将placeId保存到NSUserDefaults

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view 
calloutAccessoryControlTapped:(UIControl *)control
{
    NSString *passedId = view.annotation.subtitle;
    [[NSUserDefaults standardUserDefaults]
    setObject:passedId forKey:@"passedId"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

1 个答案:

答案 0 :(得分:5)

为什么不在自定义地图视图注释中添加新属性? 在 MapViewAnnotation.h 添加

@property (nonatomic, strong) NSString *passedID;

然后,在viewcontroller中的注释创建中,设置该属性而不是设置字幕:

newAnnotation = [[MapViewAnnotation alloc] initWithTitle:dictionary[@"placeName"]
                                               andCoordinate:location];

newAnnotation.passedID = dictionary[@"placeId"];

最后,在 CalloutAccessoryControlTapped 中,将MapViewAnnotation强制转换为自定义类,然后访问passID属性,而不是字幕属性:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view 
calloutAccessoryControlTapped:(UIControl *)control
{
    NSString *passedId = ((MapViewAnnotation*)view.annotation).passedID;
    [[NSUserDefaults standardUserDefaults]
    setObject:passedId forKey:@"passedId"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}