【问题标题】:How to access to an annotation attribute inside method calloutAccessoryControlTapped如何访问方法 calloutAccessoryControlTapped 中的注释属性
【发布时间】:2014-03-22 01:37:35
【问题描述】:

当用户点击地图注释中的标注时,我正在尝试打开详细视图控制器。

我创建了一个名为 myAnnotation 的自定义注释子类,并在其中包含了一个名为 idEmpresa 的属性。

在自定义方法中,我将注释声明如下:

double latitud = [[[categorias objectAtIndex:i] objectForKey:@"latitud"] doubleValue];

double longitud = [[[categorias objectAtIndex:i] objectForKey:@"longitud"]doubleValue];

CLLocationCoordinate2D lugar;
lugar.latitude = latitud;
lugar.longitude = longitud;

NSString *nombre = [[categorias objectAtIndex:i] objectForKey:@"titulo"];              

CLLocationCoordinate2D coordinate3;
coordinate3.latitude = latitud;
coordinate3.longitude = longitud;
myAnnotation *annotation3 = [[myAnnotation alloc] initWithCoordinate:coordinate3 title:nombre ];

annotation3.grupo = 1;

int number = [[[categorias objectAtIndex:i] objectForKey:@"idObjeto"] intValue];

annotation3.idEmpresa = number;
NSLog(@"ESTA ES LA ID DE LA EMPRESA %d",number);
[self.mapView addAnnotation:annotation3];

你可能会看到注解有一个属性annotation3.idEmpresa

然后,在calloutAccessoryControlTapped 方法中,我需要访问该属性。我知道如何访问该方法中的注释标题和副标题:

NSString *addTitle = [[view annotation] title  ];
NSString *addSubtitle = [[view annotation] subtitle  ];

但它不适用于属性 idEmpresa

NSString *addTitle = [[view annotation] title  ];

【问题讨论】:

    标签: ios mkmapview mkannotation mkannotationview


    【解决方案1】:

    MKAnnotationView 中的annotation 属性通常键入为id<MKAnnotation>

    这意味着它将指向一些实现MKAnnotation 协议的对象。
    该协议仅定义了三个标准属性(titlesubtitlecoordinate)。

    您的自定义类myAnnotation 实现了MKAnnotation 协议,因此具有三个标准属性以及一些自定义属性。

    因为annotation 属性是通用类型的,所以编译器只知道三个标准属性,如果您尝试访问不在标准协议中的自定义属性,编译器会给出警告或错误。

    要让编译器知道在这种情况下annotation 对象是具体 myAnnotation 的一个实例,您需要对其进行强制转换,以便它可以让您访问自定义属性而不会出现警告或错误(代码完成也将开始帮助您)。

    在强制转换之前,使用isKindOfClass: 检查对象是否真的属于您想要强制转换的类型,这一点很重要。如果您将一个对象转换为一个实际上不是的类型,您很可能最终会在运行时生成异常。

    例子:

    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
    {   
        if ([view.annotation isKindOfClass:[myAnnotation class]])
        {
            myAnnotation *ann = (myAnnotation *)view.annotation;
            NSLog(@"ann.title = %@, ann.idEmpresa = %d", ann.title, ann.idEmpresa);
        }
    }
    

    【讨论】:

    • 谢谢你,安娜,它很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多