如果,正如你所说,“这在iOS 6中确实有效”,你应该考虑一下
相当地
幸运的是,它确实做到了(或似乎做到了),这种设置注释图像的方法在任何版本下都不应该依赖。
尽管@Ar-Ma正确地认为注释视图
annotation
属性(以防视图被重新使用),这不会解决主要问题。
注释视图的
image
基于的值设置
categoryIdNumber
这似乎是一些变量
外部
这个
viewForAnnotation
委托方法。
你
不能
假设:
-
查看注释
你打电话后会立即打电话
addAnnotation
。即使在iOS 6或更早版本中,这也不能保证。
-
查看注释
将仅为每个注释调用一次。当用户平移或缩放地图,并且注释返回屏幕时,可以为同一注释多次调用委托方法。
-
查看注释
将以与添加注释相同的顺序调用。这是第1点和第2点的结果。
我想就在你打电话之前
添加注释
这个
类别ID编号
被正确地设置,然后基于上述不正确的假设,
查看注释
使用
类别ID编号
以设置图像。
现在的情况是
查看注释
正在被地图视图调用
添加注释
调用在哪个点完成
类别ID编号
可能是与添加的最后一个注释相关的值,并且所有注释都使用适用于最后一个批注的图像。
要解决此问题(
不管
iOS版本的),您必须将
类别ID编号
值输入到每个注释对象中
之前
使命感
添加注释
.
看起来你的注释类是
MyAnnotation
而你已经有了
catMapId
属性。
必须在注释中设置此属性
之前
使命感
添加注释
--不是
在…内
这个
查看注释
方法为时已晚。(顺便说一句,您正在创建
我的注释
对象
在…内
这个
查看注释
这种方法毫无意义。)
因此,在创建和添加注释的位置(不在
查看注释
):
MyAnnotation* myAnn = [[MyAnnotation alloc] init];
myAnn.coordinate = ...
myAnn.title = ...
myAnn.catMapId = categoryIdNumber; // <-- set catMapId BEFORE addAnnotation
[mapView addAnnotation:myAnn];
然后代码进入
查看注释
应该是这样的:
- (MKAnnotationView *) mapView:(MKMapView *)mapingView viewForAnnotation:(id <MKAnnotation>) annotation
{
annView = nil;
if(annotation != mapingView.userLocation)
{
static NSString *defaultPinID = @"MyAnnId";
annView = (MKAnnotationView *)[mapingView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( annView == nil )
{
annView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] ;
annView.canShowCallout = YES;
}
else
{
//view is being re-used, re-set annotation to current...
annView.annotation = annotation;
}
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
annView.rightCalloutAccessoryView = rightButton;
//Make sure we have a MyAnnotation-type annotation
if ([annotation isKindOfClass:[MyAnnotation class]])
{
//Do not CREATE a local MyAnnotation object here.
//Instead, get the catMapId from the annotation object
//that was PASSED INTO the delegate method.
//MyAnnotation* annotation= [MyAnnotation new];
//annotation.catMapId = categoryIdNumber;
MyAnnotation *myAnn = (MyAnnotation *)annotation;
//The value of the external variable categoryIdNumber is irrelevant here.
//NSLog(@"categoryIdNumber %@",categoryIdNumber);
NSLog(@"myAnn.catMapId %@",myAnn.catMapId);
//Put the NSNumber value into an int to simplify the code below.
int myAnnCatMapId = [myAnn.catMapId intValue];
NSString *imageName = nil;
switch (myAnnCatMapId)
{
case 9:
{
imageName = @"PIN_comprare.png";
break;
}
case 10:
{
imageName = @"PIN_mangiare.png";
break;
}
case 11:
{
imageName = @"PIN_mangiare.png";
break;
}
case 12:
{
imageName = @"PIN_vivere.png";
break;
}
default:
{
//set some default image for unknown cat ids...
imageName = @"default.png";
break;
}
}
annView.image = [UIImage imageNamed:imageName];
NSLog(@"annview %d", myAnnCatMapId);
}
}
return annView;
}