4

我正在尝试执行通过 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"];

MapViewController.m 中的 CalloutAccessoryControlTapped - 在这里您可以看到我将 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];
}
4

1 回答 1

5

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

@property (nonatomic, strong) NSString *passedID;

然后,在视图控制器中创建注释时,设置该属性而不是设置字幕:

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

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

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

- (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];
}
于 2013-02-13T11:41:25.173 回答