Mapkit с несколькими аннотациями (выносками), отображающими следующий вид - PullRequest
1 голос
/ 15 августа 2010

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

Вот сенарио.Я размещаю несколько аннотаций на карте, когда пользователь выполняет поиск, например, пиццу.Добавлена ​​кнопка для правого вида аннотации, при нажатии которой открывается следующий подробный вид.Проблема в том, как отправить некоторую информацию в следующее представление, например, я добавляю индекс к аннотациям при их создании, теперь я хочу получить доступ к этой информации из аннотации и передать ее следующему представлению с помощью селектора, установленного на кнопке.

Я проверил все карты деликатно, но не нашел ни одного, где я мог бы сопоставить эту информацию со следующим видом и аннотацией.

Надеюсь, я не запутал вас, ребята, в моем вопросе.Пожалуйста, дайте мне знать, что я перефразирую его.

Заранее спасибо.

Ответы [ 3 ]

9 голосов
/ 15 августа 2010

Когда вы создаете UIButton для аннотации, присвойте свойству tag (тег является свойством NSInteger UIView) идентификатор или индекс массива, который идентифицирует соответствующий объект. Затем вы можете извлечь это значение тега из параметра sender в ваш селектор.


Редактировать : вот пример кода.

Вы создаете представление аннотации и связываете кнопку в -mapView вашего делегата: viewForAnnotation: method:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    // Boilerplate pin annotation code
    MKPinAnnotationView *pin = (MKPinAnnotationView *) [self.map dequeueReusableAnnotationViewWithIdentifier: @"restMap"];
    if (pin == nil) {
        pin = [[[MKPinAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"restMap"] autorelease];
    } else {
        pin.annotation = annotation;
    }
    pin.pinColor = MKPinAnnotationColorRed
    pin.canShowCallout = YES;
    pin.animatesDrop = NO;

    // now we'll add the right callout button
    UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    // customize this line to fit the structure of your code.  basically
    // you just need to find an integer value that matches your object in some way:
    // its index in your array of MKAnnotation items, or an id of some sort, etc
    // 
    // here I'll assume you have an annotation array that is a property of the current
    // class and we just want to store the index of this annotation.
    NSInteger annotationValue = [self.annotations indexOfObject:annotation];

    // set the tag property of the button to the index
    detailButton.tag = annotationValue;

    // tell the button what to do when it gets touched
    [detailButton addTarget:self action:@selector(showDetailView:) forControlEvents:UIControlEventTouchUpInside];

    pin.rightCalloutAccessoryView = detailButton;
    return pin;

}

Затем в вашем методе действия вы распакуете значение из tag и будете использовать его для отображения нужной детали:

-(IBAction)showDetailView:(UIView*)sender {
    // get the tag value from the sender
    NSInteger selectedIndex = sender.tag;
    MyAnnotationObject *selectedObject = [self.annotations objectAtIndex:selectedIndex];

    // now you know which detail view you want to show; the code that follows
    // depends on the structure of your app, but probably looks like:
    MyDetailViewController *detailView = [[MyDetailViewController alloc] initWithNibName...];
    detailView.detailObject = selectedObject;

    [[self navigationController] pushViewController:detailView animated:YES];
    [detailView release];
}
1 голос
/ 15 марта 2012

Другой вариант:

Вы можете реализовать следующие методы:

- (void)mapView:(MKMapView *)mapView didSelectAnnotation:(MKAnnotationView *)view;
- (void)mapView:(MKMapView *)mapView didDeselectAnnotation:(MKAnnotationView *)view;
1 голос
/ 09 декабря 2010

Можно ли, например, в представлении «Аннотация» получить заголовок или субтитры или любую другую информацию, которую вы использовали при создании выводов?Я хочу, чтобы в аннотации было всплывающее окно с определенным изображением, основанное на одной из этих переменных.

#import "MapPin.h"

@implementation MapPin


@synthesize coordinate;
@synthesize title;
@synthesize subtitle;
@synthesize indexnumber;
@synthesize imageFile;

-(id)initWithCoordinates:(CLLocationCoordinate2D)location
               placeName: placeName
             description:description
                indexnum:indexnum
            imageFileLoc:imageFileLoc{

    self = [super init];
    if (self != nil) {
        imageFile=imageFileLoc;
        [imageFile retain];
        indexnumber=indexnum;
        [indexnumber retain];
        coordinate = location;
        title = placeName;
        [title retain];
        subtitle = description;
        [subtitle retain];
    }
    return self;

}



-(void)addAnnotations {

    // Normally read the data for these from the file system or a Web service
    CLLocationCoordinate2D coordinate = {35.9077803, -79.0454936};
    MapPin *pin = [[MapPin alloc]initWithCoordinates:coordinate
                                          placeName:@"Keenan Stadium"
                                        description:@"Tar Heel Football"
                                            indexnum:@"1"
                                        imageFileLoc:@"owl.jpg"];
    [self.map addAnnotation:pin];
...