2013-02-13 33 views
4

我想執行通過MKAnnotation傳遞自定義屬性(placeId)的簡單功能。我用一個名爲「MapViewAnnotation」的自定義類來設置所有內容。通過MKAnnotation傳遞自定義屬性CalloutAccessoryControlTapped

我想在用戶激活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]; 
} 
+0

你能解釋一下更好的問題是什麼?你在某處遇到異常嗎?當你試圖檢索它時,它會通過IdI nil? – 2013-02-13 11:01:48

+0

上面顯示的代碼工作正常 - 但它使placeId對用戶可見,作爲註釋的副標題。我想通過使用自定義類來使placeId不可見。我一直在嘗試一次又一次,但無法做到。 – Brandon 2013-02-13 11:05:07

回答

5

你爲什麼不您的自定義地圖視圖標註添加新的特性? 在MapViewAnnotation.h在ViewController中添加

@property (nonatomic, strong) NSString *passedID; 

然後,在你的註釋創建,您可以設置的,而不是設置字幕該屬性:

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

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

最後,在CalloutAccessoryControlTapped,您將MapViewAnnotation轉換爲您的自定義類,然後訪問passedID屬性,而不是字幕屬性:

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

IT WORKS !!!!!你太棒了!!!! – Brandon 2013-02-13 11:49:16

+1

不客氣:) – 2013-02-13 11:56:02

+0

認真 - 爲我節省了很多時間。謝謝! – Brandon 2013-02-13 11:57:10

相關問題