Bra*_*don 4 objective-c mapkit mkmapview mkannotation ios
我正在尝试执行通过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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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"];
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
为什么不在自定义地图视图注释中添加新属性?在MapViewAnnotation.h中添加
@property (nonatomic, strong) NSString *passedID;
Run Code Online (Sandbox Code Playgroud)
然后,在viewcontroller中的注释创建中,设置该属性而不是设置字幕:
newAnnotation = [[MapViewAnnotation alloc] initWithTitle:dictionary[@"placeName"]
andCoordinate:location];
newAnnotation.passedID = dictionary[@"placeId"];
Run Code Online (Sandbox Code Playgroud)
最后,在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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1577 次 |
| 最近记录: |