[英]User location image pin disappears most of time
i Am using following code 我正在使用以下代码
-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([[annotation title] isEqualToString:@"Current Location"] )
{
MKAnnotationView *anView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentPin"];
anView.image = [UIImage imageNamed:@"pin_green.png"];
anView.canShowCallout = true;
anView.enabled = true;
return anView;
}
The issue is, it randomly disappears and appears again. 问题是,它随机消失并再次出现。 Giving a very bad user experience. 给用户带来非常糟糕的体验。 Any way to fix this? 有任何解决这个问题的方法吗?
You should use MKMapView's dequeueReusableAnnotationViewWithIdentifier:
and see if you get a view back before creating a new one with initWithAnnotation:reuseIdentifier:
: 您应该使用MKMapView的dequeueReusableAnnotationViewWithIdentifier:
并在使用initWithAnnotation:reuseIdentifier:
创建新视图之前查看是否获得了视图:
MKAnnotationView *anView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"currentPin"];
if (!anView) {
anView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentPin"];
anView.image = [UIImage imageNamed:@"pin_green.png"];
anView.canShowCallout = true;
anView.enabled = true;
}
return anView;
That said, I'm not entirely sure this is the cause of your problem. 就是说,我不完全确定这是造成您问题的原因。
There are several suspect things about this code: 此代码有一些可疑之处:
You're not using dequeue
, as someone has pointed out. 有人指出,您没有使用dequeue
。 In particular, the problem here is that you are making a new view every single time, rather than checking to see whether a new view needs making. 特别是,这里的问题是您每次都在创建一个新视图,而不是检查是否需要创建新视图。
You are forgetting the key step, namely, to associate the view with the annotation. 您忘记了关键步骤,即将视图与注释相关联。
Here is the canonical structure of a simple viewForAnnotation:
implementation where we supply our own view: 这是一个简单的viewForAnnotation:
实现的规范结构,其中提供了我们自己的视图:
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>)annotation {
MKAnnotationView* v = nil;
if ([annotation.title isEqualToString:@"Current Location"]) {
static NSString* ident = @"greenPin";
v = [mapView dequeueReusableAnnotationViewWithIdentifier:ident];
if (v == nil) {
v = [[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:ident];
v.image = [UIImage imageNamed:@"pin_green.png"];
v.canShowCallout = YES;
}
v.annotation = annotation;
}
return v;
}
Since that code works for me, I'd suggest you start with it and tweak it as necessary. 由于该代码对我有用,因此建议您从它开始,并根据需要进行调整。
By the way, you do NOT need this method just to get a green pin! 顺便说一句,您并不需要仅使用绿色针脚就可以使用此方法! You do know that, right? 你知道吗? iOS will give you a green pin (MKPinAnnotationColorGreen). iOS将为您提供一个绿色的图钉(MKPinAnnotationColorGreen)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.