How to access to an annotation attribute inside method calloutAccessoryControlTapped

前端 未结 1 1135
孤独总比滥情好
孤独总比滥情好 2020-12-20 06:16

I am trying to open a detail viewController when a user taps on the callout from a map annotation.

I have created a custom annotation subclass called myAnnotation, a

相关标签:
1条回答
  • 2020-12-20 06:46

    The annotation property in MKAnnotationView is typed generically as id<MKAnnotation>.

    That means it will point to some object that implements the MKAnnotation protocol.
    That protocol only defines three standard properties (title, subtitle, and coordinate).

    Your custom class myAnnotation implements the MKAnnotation protocol and so has the three standard properties but also some custom ones.

    Because the annotation property is typed generically, the compiler only knows about the three standard properties and gives warnings or errors if you try to access custom properties that are not in the standard protocol.

    To let the compiler know that the annotation object in this case is specifically an instance of myAnnotation, you need to cast it so that it will let you access the custom properties without warnings or errors (and the code completion will also start helping you).

    Before casting, it's important to check that the object really is of the type you want to cast it to using isKindOfClass:. If you cast an object to a type that it really isn't, you'll most likely end up generating exceptions at run-time.

    Example:

    - (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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题