gpt4 book ai didi

ios - 通过 MKAnnotation CalloutAccessoryControlTapped 传递自定义属性

转载 作者:可可西里 更新时间:2023-11-01 05:37:04 25 4
gpt4 key购买 nike

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

最佳答案

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

@property (nonatomic, strong) NSString *passedID;

然后,在 View Controller 中创建注释时,设置该属性而不是设置副标题:

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

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

最后,在您的 CalloutAccessoryControlTapped 中,您将 MapViewAnnotation 转换为您的自定义类,然后访问 passedID 属性,而不是 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];
}

关于ios - 通过 MKAnnotation CalloutAccessoryControlTapped 传递自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14851831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com