Как добавить выноску в отдельную аннотацию в виде карты

Я пытаюсь установить каждую аннотацию с различной подробной информацией о выноске.

В настоящее время, когда я нажимаю на любое место аннотации, отображается вся информация о выноске.

#import "AnnotationViewController.h"
#import "Annotation.h"

@implementation AnnotationViewController
@synthesize mapView;

-(void)viewDidLoad {

    [super viewDidLoad];
    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    [mapView setDelegate:self];

    MKCoordinateRegion TT = { {0.0, 0.0} , {0.0, 0.0} };
    TT.center.latitude = 43.65343;
    TT.center.longitude = -79.396311;
    TT.span.longitudeDelta = 0.02f;
    TT.span.latitudeDelta = 0.02f;
    [mapView setRegion:TT animated:YES];

    Annotation *ann1 = [[Annotation alloc] init];
    ann1.title = @"Annotation 01";
    ann1.subtitle = @"Message 01";
    ann1.coordinate = TT.center;
    [mapView addAnnotation:ann1];

    MKCoordinateRegion TTY = { {0.0, 0.0} , {0.0, 0.0} };
    TTY.center.latitude = 43.76919;
    TTY.center.longitude = -79.41245;
    TTY.span.longitudeDelta = 0.02f;
    TTY.span.latitudeDelta = 0.02f;
    [mapView setRegion:TTY animated:YES];

    Annotation *ann2 = [[Annotation alloc] init];
    ann2.title = @"Annotation 02";
    ann2.subtitle = @"Message 02";
    ann2.coordinate = TTY.center;
    [mapView addAnnotation:ann2];

}


-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:id<MKAnnotation>)annotation
{
    MKPinAnnotationView *view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pin"];
    view.pinColor = MKPinAnnotationColorPurple;
    view.enabled = YES;
    view.animatesDrop = YES;
    view.canShowCallout = YES;

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"GPSicon.png"]];
    view.leftCalloutAccessoryView = imageView;
    view.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    return view;

}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    NSString *msg = [@"Location 01" stringByAppendingFormat:@"Opening 01"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Plaza 01" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];

    NSString *msg02 = [@"Location 02" stringByAppendingFormat:@"Opening 02"];
    UIAlertView *alert02 = [[UIAlertView alloc] initWithTitle:@"Plaza 02" message:msg02 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert02 show];

}


-(void)button:(id)sender {

    NSLog(@"Button action");

}

- (void)dealloc
{

}

- (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.
}

#pragma mark - View lifecycle

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad
 {
 [super viewDidLoad];
 }
 */

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

end

Вот что происходит: когда я нажимаю «Аннотацию 01», появляется пузырь. Но когда я нажимаю на выноску «значок сведений», появляются всплывающие заголовки «Местоположение 01» и «Местоположение 2».


Спасибо Анна за помощь. Но я все равно получаю 2 выноски, когда проверяю одну аннотацию. Это код сейчас..

#import "AnnotationViewController.h"
#import "Annotation.h"

@implementation AnnotationViewController
@synthesize mapView;

-(void)viewDidLoad {

[super viewDidLoad];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
[mapView setDelegate:self];

MKCoordinateRegion TT = { {0.0, 0.0} , {0.0, 0.0} };
TT.center.latitude = 43.65343;
TT.center.longitude = -79.396311;
TT.span.longitudeDelta = 0.02f;
TT.span.latitudeDelta = 0.02f;
[mapView setRegion:TT animated:YES];

Annotation *ann1 = [[Annotation alloc] init];
ann1.title = @"Annotation 01";
ann1.subtitle = @"Message 01";
ann1.coordinate = TT.center;
[mapView addAnnotation:ann1];

MKCoordinateRegion TTY = { {0.0, 0.0} , {0.0, 0.0} };
TTY.center.latitude = 43.76919;
TTY.center.longitude = -79.41245;
TTY.span.longitudeDelta = 0.02f;
TTY.span.latitudeDelta = 0.02f;
[mapView setRegion:TTY animated:YES];

Annotation *ann2 = [[Annotation alloc] init];
ann2.title = @"Annotation 02";
ann2.subtitle = @"Message 02";
ann2.coordinate = TTY.center;
[mapView addAnnotation:ann2];

}


-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:id<MKAnnotation>)annotation
{
MKPinAnnotationView *view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pin"];
view.pinColor = MKPinAnnotationColorPurple;
view.enabled = YES;
view.animatesDrop = YES;
view.canShowCallout = YES;

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"GPSicon.png"]];
view.leftCalloutAccessoryView = imageView;
view.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

return view;

}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
//first make sure the annotation is our custom class...
if ([view.annotation isKindOfClass:[Annotation class]])
{
    //cast the object to our custom class...
    Annotation *ann1 = (Annotation *)view.annotation;

    //show one alert view with title set to annotation's title
    //and message set to annotation's subtitle...
    UIAlertView *alert = [[UIAlertView alloc] 
                             initWithTitle:ann1.title 
                             message:ann1.subtitle 
                             delegate:self 
                             cancelButtonTitle:@"OK" 
                             otherButtonTitles:nil];

    [alert show];
}
    //first make sure the annotation is our custom class...
if ([view.annotation isKindOfClass:[Annotation class]])
{
    //cast the object to our custom class...
    Annotation *ann2 = (Annotation *)view.annotation;

    //show one alert view with title set to annotation's title
    //and message set to annotation's subtitle...
    UIAlertView *alert2 = [[UIAlertView alloc] 
                             initWithTitle:ann2.title 
                             message:ann2.subtitle 
                             delegate:self 
                             cancelButtonTitle:@"OK" 
                             otherButtonTitles:nil];

    [alert show];
}
}


-(void)button:(id)sender {

NSLog(@"Button action");

}

- (void)dealloc
{

}

- (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.
}

#pragma mark - View lifecycle

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

end

Код моего файла Annotation.m

#import "Annotation.h"


@implementation Annotation
@synthesize coordinate, title, subtitle;

-(void)dealloc {


}

@end

Мой код файла Annotation.h

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


@interface Annotation : NSObject <MKAnnotation> {

CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;

}

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

@end

Должен ли я создавать много файлов h/m для каждой аннотации, чтобы сделать выноску другой? я просто топаю в этот момент. любые предположения будут отличными, спасибо!


person user3268096    schedule 04.02.2014    source источник
comment
Пожалуйста, не показывайте два вида предупреждений. Просто покажите один, как в моем примере.   -  person    schedule 04.02.2014
comment
Извините, я не ясно выражаюсь. Я пытаюсь заставить его показывать другую информацию о выноске, а не информацию о всплывающих окнах. с каждой аннотацией.   -  person user3268096    schedule 05.02.2014


Ответы (1)


В calloutAccessoryControlTapped код показывает два представления предупреждений с жестко запрограммированным текстом для заголовка и сообщения одно за другим. Так что это то, что вы получаете, очевидно.

В методе calloutAccessoryControlTapped объект аннотации, кнопка выноски которого была нажата, доступен через view.annotation.

Параметр view — это параметр MKAnnotationView, который имеет свойство annotation, указывающее на связанную с ним аннотацию.

Поэтому измените код, чтобы он отображал только один вид предупреждений с заголовком и сообщением на основе свойств объекта аннотации.

Также рекомендуется проверить класс аннотации, чтобы убедиться, что это тот тип аннотации, который вы ожидаете.

Например:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    //first make sure the annotation is our custom class...
    if ([view.annotation isKindOfClass:[Annotation class]])
    {
        //cast the object to our custom class...
        Annotation *ann = (Annotation *)view.annotation;

        //show one alert view with title set to annotation's title
        //and message set to annotation's subtitle...
        UIAlertView *alert = [[UIAlertView alloc] 
                                 initWithTitle:ann.title 
                                 message:ann.subtitle 
                                 delegate:self 
                                 cancelButtonTitle:@"OK" 
                                 otherButtonTitles:nil];

        [alert show];
    }
}
person Community    schedule 04.02.2014
comment
Извините, я не ясно выражаюсь. Я пытаюсь заставить его показывать другую информацию о выноске, а не информацию о всплывающих окнах. с каждой аннотацией - person user3268096; 05.02.2014
comment
Добавьте информацию, которую вы хотите показать, в свой класс аннотаций. Установите эту информацию при создании каждой аннотации. Затем в calloutAccessoryControlTapped получите доступ к этой информации так же, как в примере доступ к заголовку и подзаголовку. - person ; 05.02.2014
comment
Можете ли вы показать мне пример сценария? я новичок в самом xcode. большое спасибо за попытку помочь мне. - person user3268096; 05.02.2014
comment
comment
он по-прежнему показывает все выноски в одной аннотации. Анна, можно ли мне заплатить/нанять тебя, чтобы ты мне помогла? У меня мало времени, и мне нужно закончить этот проект. пожалуйста, дайте мне знать. вы можете связаться со мной [email protected] - person user3268096; 06.02.2014