Iphone 用户位置图像pin大部分时间消失
我正在使用以下代码Iphone 用户位置图像pin大部分时间消失,iphone,objective-c,xcode,Iphone,Objective C,Xcode,我正在使用以下代码 -(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { if ([[annotation title] isEqualToString:@"Current Location"] ) { MKAnnotationView *anView = [[MKAnnotationView alloc]
-(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;
}
-(MKAnnotationView*)地图视图:(MKMapView*)地图视图注释:(id)注释
{
if([[annotation title]isEqualToString:@“当前位置”])
{
MKAnnotationView*anView=[[MKAnnotationView alloc]initWithAnnotation:annotation重用标识符:@“currentPin”];
anView.image=[UIImage ImageName:@“pin_green.png”];
anView.canShowCallout=true;
anView.enabled=true;
返回视图;
}
问题是,它会随机消失并再次出现。用户体验非常糟糕。是否有办法解决此问题?您应该使用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;
也就是说,我不完全确定这是您的问题的原因。此代码有几个可疑之处:
- 正如有人指出的那样,您没有使用“出列”。特别是,这里的问题是,您每次都在创建一个新视图,而不是检查是否需要创建一个新视图
- 您忘记了关键步骤,即将视图与注释关联
视图的规范结构,用于说明:
实现,其中我们提供了自己的视图:
- (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;
}
-(MKAnnotationView*)映射视图:(MKMapView*)映射视图
viewForAnnotation:(id)注释{
MKAnnotationView*v=nil;
如果([annotation.title isEqualToString:@“当前位置”]){
静态NSString*ident=@“绿色PIN”;
v=[mapView dequeueReusableAnnotationViewWithIdentifier:Identity];
如果(v==nil){
v=[[MKAnnotationView alloc]initWithAnnotation:annotation
重用标识符:ident];
v、 image=[UIImage ImageName:@“pin_green.png”];
v、 canShowCallout=是;
}
v、 注释=注释;
}
返回v;
}
既然这段代码适合我,我建议你从它开始,并根据需要进行调整
顺便说一句,你不需要这个方法就可以得到一个绿色的pin!你知道的,对吧?iOS会给你一个绿色的pin(MKPinAnnotationColorGreen).显然,这段代码不是问题所在。问题应该在于您在某个时间点删除所有注释并添加它们again@Eugene真是个愚蠢的错误。我感到很尴尬。谢谢你指出。修正了。