我有一个用于我的 MKAnnotations 的自定义类,我想覆盖默认的 mapView:viewForAnnotatation
方法,以便我可以在标注中添加额外的信息。当我在代码中设置我的委托(delegate)时(按照下面的代码),注释被放置在 map 上并且可以选择,但我的 mapView:viewForAnnoation
从未被调用。
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
NSLog(@"viewForAnnotation: called");
MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"mapPin"];
if(!aView){
aView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"mapPin"];
}
aView.annotation = annotation;
return aView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.mapView.delegate = self;
}
我知道委托(delegate)正在设置,因为我可以覆盖方法 -(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
当我选择一个注释。
当我从在代码中设置委托(delegate)更改为在 Storyboard 中设置时,调用方法(NSLog(@"viewForAnnotation: called"); 语句出现)但注释没有出现在 map 上,有时会出现此错误出现:
<Error>: ImageIO: CGImageReadSessionGetCachedImageBlockData *** CGImageReadSessionGetCachedImageBlockData: bad readSession [0x8618480]
最佳答案
这似乎是两个不同的问题:
关于代码 v Storyboard中的设置委托(delegate),很难调和您的各种观察(委托(delegate)方法
didSelectAnnotationView
在两种情况下都被调用,但是viewForAnnotation
是不是)。在 Storyboard的代码 v 中设置它之间的唯一区别是设置delegate
的时间。您没有向我们展示添加注释的过程,因此很难根据您所描述的内容进行诊断。如果你的委托(delegate)方法都没有被调用,我会怀疑mapView
IBOutlet
,但如果有些方法有效而其他方法无效,我只能怀疑是时间问题.关于
MKAnnotationView
的设置,默认实现什么都不做。您需要编写自己的MKAnnotationView
子类,如果您使用自己的图像则设置其图像,或者更简单,只需使用MKPinAnnotationView
。但是仅仅创建一个MKAnnotationView
不会做任何事情。你真的想要:- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{ // If it's the user location, just return nil. if ([annotation isKindOfClass:[MKUserLocation class]]) return nil; // Handle any custom annotations. MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"mapPin"]; if(aView){ aView.annotation = annotation; } else { aView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"mapPin"]; } aView.canShowCallout = NO; return aView; }
(请注意,我不仅要创建一个
MKPinAnnotationView
,而且还要确保它不是一个MKUserLocation
,以防您选择向用户显示 map 上的位置。我还将显式设置canShowCallout
,因为这可能是您编写此方法的根本原因。)
最重要的是,如果您想显示一个简单的引脚注释 View ,请使用 MKPinAnnotationView
。单独使用 MKAnnotationView
将不会显示任何注释。
关于iphone - map View :viewForAnnotation: not called when delegate set in code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15862618/