2010-10-19 3 views
2

Я боролся с этим в течение нескольких дней, я даже переписал половину кода, чтобы попробовать его по-другому.mapkit, помещая кнопку раскрытия с индексом аннотации

У меня есть мои аннотации, импортированные из csv и помещенные на карту с плиткой и субтитрами, я тщетно пытаюсь добавить тег к кнопкам раскрытия, чтобы я мог видеть, какой из них был использован, но имеет проблемы, любые значения Я назначаю аннотацию, я не могу получить к ним доступ (например, индекс), я могу получить доступ к заголовку и субтитрам, но это так.

как я присвоить индекс аннотации, что я могу затем добавить к кнопке в качестве тега, так что я могу записать кран

вот мой код

 NSURL *dataUrl = [NSURL URLWithString:@"http://nne.ezadspro.co.uk/cms/testmap.txt"]; 
    // URLWithString:@"http://neic.usgs.gov/neis/gis/qed.asc"]; 
    NSString *fileString = [NSString stringWithContentsOfURL:dataUrl 
                encoding:NSUTF8StringEncoding 
                 error:nil]; 
    int count = 0; 
    NSScanner *scanner = [NSScanner scannerWithString:fileString]; 

    points = [[NSMutableArray array] retain]; 
    AnnotationData *event; 
    NSString *line; 
    NSArray *values; 
    while ([scanner isAtEnd] == NO) { 
     [scanner scanUpToString:@"\n" intoString:&line]; 
     //skip the first line 
     if(count > 0) { 
      values = [line componentsSeparatedByString:@","]; 
      event = [[[AnnotationData alloc] init] autorelease]; 
      event.latitude = [[values objectAtIndex:5] floatValue]; 
      event.longitude = [[values objectAtIndex:6] floatValue]; 
      event.companyID = [[values objectAtIndex:0]intValue]; 
      event.title = [values objectAtIndex:1]; 
      event.subtitle = [values objectAtIndex:2]; 
      //event.magnitude = [[values objectAtIndex:4] floatValue]; 
      //event.depth = [[values objectAtIndex:5] floatValue]; 
      //NSLog(@"%@",event.companyID); 
      [points addObject:event]; 

     } 
     count++; 
     if(count == 300) { 
      //limit number of events to 300 
      break; 
     } 
    } 



    for (int i=0; i<points.count; i++) { 
     AnnotationData *annData = [points objectAtIndex:i]; 


     coordinate.latitude = annData.latitude; 
     coordinate.longitude = annData.longitude; 
     CLLocationCoordinate2D newCoord = {coordinate.latitude, coordinate.longitude}; 
     PlaceAnnotation* annotation = [[PlaceAnnotation alloc] initWithCoordinate:newCoord andID:i]; 
     annotation.mTitle = annData.title; 
     annotation.mSubtitle = annData.subtitle; 
     annotation.indexID = i; 

     //annotation.indexID = [[i]intValue]; 


     [mapView addAnnotation:annotation]; 

     [annotation release]; 

    } 


} 




- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

- (void)viewDidUnload { 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 




- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    MKPinAnnotationView *pinAnnotation = nil; 
    if(annotation != mV.userLocation) 
    { 
     static NSString *defaultPinID = @"myPin"; 
     pinAnnotation = (MKPinAnnotationView *)[mV dequeueReusableAnnotationViewWithIdentifier:defaultPinID]; 
     if (pinAnnotation == nil) 
      pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease]; 

     pinAnnotation.canShowCallout = YES; 

     //instatiate a detail-disclosure button and set it to appear on right side of annotation 
     UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 
     pinAnnotation.rightCalloutAccessoryView = infoButton; 





     //infoButton.tag = 
     //[infoButton addTarget:self action:@selector(onMapVenueSelect) forControlEvents:UIControlEventTouchUpInside]; 
     //defaultPinID.rightCalloutAccessoryView = infoButton; 
     //infoButton.tag = [event indexOfObject:tmpVenueData]; 
     // [defaultPinID release]; 

    } 

    return pinAnnotation; 
    [pinAnnotation release]; 
} 

благодаря

ответ

3

Рассмотрите возможность использования протокола MKAnnation и хранения всех необходимых вам идентификаторов или данных.

Заголовок точка Отправной может пойти что-то вроде этого:

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 
#import <CoreLocation/CoreLocation.h> 


@interface YourFancyAnnotationClass : NSObject <MKAnnotation> { 
    CLLocationCoordinate2D coordinate; 
    NSString *title; 
    NSString *subtitle; 
    NSNumber *companyID; 
} 

@property(nonatomic, assign) CLLocationCoordinate2D coordinate; 
@property(nonatomic, copy) NSString *title; 
@property(nonatomic, copy) NSString *subtitle; 
@property(nonatomic, copy) NSNumber *companyID; 



@end 




Then in your delegate do something like this... 

    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control 
    { 
     NSLog(@"calloutAccessoryControlTapped:"); 
     YourFancyAnnotationClass *tappedSite = (SiteAnnotation *)[view annotation]; 
     NSNumber *companyIDThatWasClickedExample = [tappedSite companyID]; 

и т.д ...

+0

я уже делаю это, но когда я пытаюсь и добавить тег в методе viewForAnnotation, он просто возвращает 0, каждый раз. есть ли причина, по которой вы использовали NSNumber вместо NSUInteger? –

+0

Почему вы используете тег? Я не уверен, что я понимаю точку тега в этом сценарии. Просто доступ к собственности, в которой вы нуждаетесь. NSUInteger будет хорошо и просто. – Nick

+0

Я добавил пример того, как получить доступ к идентификатору с помощью метода делегат-аксессуар, контролируемый делегатом. – Nick

Смежные вопросы