在里面
viewForAnnotation
,而不是“获取管脚的索引”(这会有效,但效率比使用
UITableView
),我建议将所需的数据添加到注释类本身。
这样,数据就更加独立,委托方法或其他地方的代码不需要担心、知道或与注释对象的位置或类型保持同步
存储
只要您有对注释对象的引用,您将立即拥有该注释所需的所有数据(或者至少它将包含对自身中相关数据的引用)。
这个
注释视图
委托方法提供对它需要视图的注释对象的引用(
annotation
参数)。它的类型一般为
id<MKAnnotation>
但它实际上是创建的确切类型的实例(
SandwichAnnotation
由您或
MKUserLocation
通过地图视图)。
一种选择是使父级
Sandwich
类本身实现
MKAnnotation
并消除
三明治注释
班这样,根本不需要搜索或引用,因为
注释
参数将实际
是
一
三明治
.
但是,您可能希望为注释对象保留一个单独的类(这很好)。在这种情况下,可以在注释类中添加对父对象的引用。例子:
@interface SandwichAnnotation : NSObject<MKAnnotation>
@property (nonatomic,assign) CLLocationCoordinate2D coordinate;
@property (nonatomic,copy) NSString * title;
@property (nonatomic,copy) NSString * subtitle;
@property (nonatomic,retain) Sandwich * whichSandwich; // <-- add reference
@end
创建
三明治注释
,设置引用
三明治
注释用于:
for (Sandwich *currentSandwich in self.sandwiches) {
SandwichAnnotation *sa = [[SandwichAnnotation alloc] init...];
sa.coordinate = ...
sa.title = ...
sa.whichSandwich = currentSandwich; // <-- set reference
[mapView addAnnotation:sa];
}
最后,在
注释视图
如果
注释
属于类型
三明治注释
,设置
leftCalloutAccessoryView
:
- (MKAnnotationView *)mapView:(MKMapView *)mv viewForAnnotation:(id <MKAnnotation>)annotation
{
if (! [annotation isKindOfClass:[SandwichAnnotation class]]) {
//If annotation is not a SandwichAnnotation, return default view...
//This includes MKUserLocation.
return nil;
}
//At this point, we know annotation is of type SandwichAnnotation.
//Cast it to that type so we can get at the custom properties.
SandwichAnnotation *sa = (SandwichAnnotation *)annotation;
NSString *annotationIdentifier = @"PinViewAnnotation";
MyAnnotationView *pinView = (MyAnnotationView *) [mv dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
if (!pinView)
{
pinView = [[MyAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
pinView.canShowCallout = YES;
//Here, just initialize a blank UIImageView ready to use.
//Set image below AFTER we have a dequeued or new view ready.
UIImageView *houseIconView = [[UIImageView alloc] init];
[houseIconView setFrame:CGRectMake(0, 0, 30, 30)];
pinView.leftCalloutAccessoryView = houseIconView;
}
else
{
pinView.annotation = annotation;
}
//At this point, we have a dequeued or new view ready to use
//and pointing to the correct annotation.
//Update image on the leftCalloutAccessoryView here
//(not just when creating the view otherwise an annotation
//that gets a dequeued view will show an image of another annotation).
UIImageView *houseIconView = (UIImageView *)pinView.leftCalloutAccessoryView;
NSString *saImageName = sa.whichSandwich.imageName;
UIImage *houseIcon = [UIImage imageNamed: saImageName];
if (houseIcon == nil) {
//In case the image was not found,
//set houseIcon to some default image.
houseIcon = someDefaultImage;
}
houseIconView.image = houseIcon;
return pinView;
}