Получение неправильной аннотации из метода MapView Delegate - PullRequest
0 голосов
/ 11 марта 2011

В моем файле .h объявлено следующее:

Annotation *annoForMoreDetails.

Однако, когда я пытаюсь установить текущую аннотацию в методе

- (MKAnnotationView *)mapView:(MKMapView *)mapViews viewForAnnotation:(id <MKAnnotation> )annotation

Он настроен не на тот объект.

Вот мой код:

 - (MKAnnotationView *)mapView:(MKMapView *)mapViews viewForAnnotation:(id <MKAnnotation> )annotation
{
    NSLog(@"welcome into the map view annotation");
    // if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    for (annotation in [mapView annotations]) {
        if ([[mapView annotations] containsObject:annotation]) {
            annoForMoreDetails = annotation;
        }
    }
    if (annoForMoreDetails.coordinate.latitude != mapViews.userLocation.coordinate.latitude && annoForMoreDetails.coordinate.longitude != mapViews.userLocation.coordinate.longitude) {
    // try to dequeue an existing pin view first
    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
    MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
                                     initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
    pinView.animatesDrop=YES;
    pinView.canShowCallout=YES;
    pinView.pinColor = MKPinAnnotationColorGreen;

    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [rightButton setTitle:annotation.title forState:UIControlStateNormal];
    [rightButton addTarget:self
                    action:@selector(moreDetails)
          forControlEvents:UIControlEventTouchUpInside];
    pinView.rightCalloutAccessoryView = rightButton;
    return pinView;
    }
    else if (annoForMoreDetails.coordinate.latitude == mapViews.userLocation.coordinate.latitude && annoForMoreDetails.coordinate.longitude == mapViews.userLocation.coordinate.longitude) {
        return nil;
    }
    return nil;
}

- (void)moreDetails {
    annotationCalloutView.frame = CGRectMake(70, 120, 188, 218);
    annotationCalloutView.alpha = 0.0;
    mapView.userInteractionEnabled = NO;
    annotationCalloutView.userInteractionEnabled = YES;
    titleLabel.text = annoForMoreDetails.title;
    titleLabel.numberOfLines = 0;
    titleLabel.userInteractionEnabled = NO;
    addressLabel.text = annoForMoreDetails.subtitle;
    [self.view addSubview:annotationCalloutView];
    [UIView beginAnimations:@"callout" context:NULL];
    [UIView setAnimationDuration:0.6];
    annotationCalloutView.alpha = 1.0;
    [UIView commitAnimations];
}

Если вы видите что-то не так, укажите это!

1 Ответ

1 голос
/ 11 марта 2011

Вы пытаетесь использовать annoForMoreDetails, чтобы узнать, какую аннотацию нажал пользователь, чтобы вы могли показать больше деталей?Если это так, есть более простой способ.Используйте метод делегата calloutAccessoryControlTapped представления карты.Он будет вызываться, когда пользователь нажимает на вспомогательную кнопку, и он передает представление аннотации, которое включает аннотацию в качестве свойства.

Удалите переменную экземпляра annoForMoreDetails, а в viewForAnnotation удалите цикл for, который устанавливает annoForMoreDetails(Я думаю, что в конечном итоге каждый раз устанавливается последняя аннотация).Удалите все другие ссылки на annoForMoreDetails.

Также в viewForAnnotation удалите строку addTarget в rightButton, поскольку вы замените свой пользовательский метод moreDetails реализацией calloutAccessoryControlTapped:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view 
    calloutAccessoryControlTapped:(UIControl *)control
{
    Annotation *annoForMoreDetails = (Annotation *)view.annotation;

    //the code currently in moreDetails method goes here...
}
...