Search code examples
objective-cmkmapviewmkannotationview

passing variable from MKAnnotationView to segue


I have an MKMapView, that I drop a number of pins on from an array. Each map pin has an MKAnnotationView that links to a segue and another controller.

All of this is working perfectly now, but I can't see how to pass a variable through the MKAnnotationView to the segue.

I can work with either passing a string or an integer, as I could pass a username as a string, or pass the id of the array and use that in the second view controller after the segue.

My working code for looping through my array, dropping the pins, adding the annotations, and then calling the segue is as below.

This all works fine, populates the map, drops the bins, and the annotations work and link to the new segue. This is all perfect!

I just need to be able to pass a variable through from the map pin array to the second view controller segue.

- (void)loadMapPins {
  for (int i=0; i<maparray.count; i++){
    Location *item = _feedItems1[i];
    CLLocationCoordinate2D myCoordinate = {[item.latitude doubleValue], [item.longitude doubleValue]};
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    point.coordinate = myCoordinate;
    point.title = item.firstname;
    point.subtitle = [NSString stringWithFormat: @"%@", item.username];
    [self.mapView addAnnotation:point];
  }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation {
  if (annotation == self.mapView.userLocation) return nil;
  static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
  MKPinAnnotationView* customPin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
  customPin.pinColor = MKPinAnnotationColorRed;
  customPin.animatesDrop = YES;
  customPin.canShowCallout = YES;
  UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
  [rightButton addTarget:self action:@selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
  customPin.rightCalloutAccessoryView = rightButton;
  return customPin;
}

- (IBAction)showDetails:(id)sender {
  [self performSegueWithIdentifier:@"showProfileFromMap" sender:self];
}

Solution

  • You should use this MKMapViewDelegate method

    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
    {
        CustomAnnotationClass *annotation = view.annotation;
        selectedAnnotationVariable = annotation.yourProperty;
        [self performSegueWithIdentifier:@"performSegue" sender:self];
    }