mapView:viewForAnnotation:方法有一个名为annotation (MKUserLocation)的参数。在我的应用程序中,我想将此annotation类型强制转换为MKAnnotation。
我试过这个:
-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MyAnnotation *myAnnotation = (MyAnnotation*)annotation;
}这里的MyAnnotation是一个采用MKAnnotation协议的自定义类。问题是myAnnotation仍然是一个MKUserLocation类型的对象。我希望myAnnotation作为MKAnnotation对象。怎么打字转换这个?请帮帮我。
发布于 2013-10-09 21:29:03
对于所有批注,无论其类型如何,都会调用viewForAnnotation委托方法。这包括地图视图自己的用户位置蓝点注释,其类型为MKUserLocation。
在强制转换annotation或尝试将其视为您的自定义类之前,您需要检查当前annotation是否属于您感兴趣的类型(或不是)。
例如:
-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if (! [annotation isKindOfClass:[MyAnnotation class]])
{
//return nil (ie. default view)
//if annotation is NOT of type MyAnnotation...
//this includes MKUserLocation.
return nil;
}
//If execution reached this point,
//you know annotation is of type MyAnnotation
//so ok to treat it like MyAnnotation...
MyAnnotation *myAnnotation = (MyAnnotation*)annotation;
//create and return custom MKAnnotationView here...
}https://stackoverflow.com/questions/19273179
复制相似问题