【发布时间】:2015-01-19 20:43:21
【问题描述】:
我想知道如何将不同的图像设置为 mapview 上的注释图钉。以下问题的区别
viewForAnnotation confusion and customizing the pinColor iteratively
Swift different images for Annotation
我的图像数组是根据服务器响应动态生成的。数组没有固定大小,因此 switch/case 构造不是一个好主意。此外,我不确定如何应用上述主题中提到的自定义类的解决方案。我知道最好对之前提出的问题之一发表评论,但不幸的是,我现在太菜鸟了,不能这样做(分数太少)。
这是在显示地图的函数内部执行的 for 循环:
for var r=0;r<arrayOfRestaurants.count;r++
{
var summonRestaurant:NSDictionary = arrayOfRestaurants[r] as NSDictionary
var nearbyRestaurant = Restaurant(nearbyRestaurants:summonRestaurant)
var latRestaurant=(nearbyRestaurant.latitude as NSString).doubleValue
var longRestaurant=(nearbyRestaurant.longitude as NSString).doubleValue
var locationOfRestaurant = CLLocationCoordinate2D(
latitude: latRestaurant as CLLocationDegrees, longitude: longRestaurant as CLLocationDegrees)
var lunchArray: NSArray = nearbyRestaurant.lunch as NSArray
var annotation = MKPointAnnotation()
annotation.setCoordinate(locationOfRestaurant)
annotation.title = nearbyRestaurant.name + " " + nearbyRestaurant.distance + " km"
map.addAnnotation(annotation)
}
这里是 viewForAnnotation 委托方法(与上述线程中使用的方法完全相同):
func mapView(map: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = map.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.pinColor = .Purple
pinView!.image = globalImageArray[0]
}
else {
pinView!.annotation = annotation
}
return pinView
}
如您所见,我为 pinView 分配了一个特定图像,即 globalImageArray[0],但我正在寻找一种解决方案,让我遍历 globalImageArray 并为每个 pin 分配特定图像。
很高兴得到任何帮助,在此先感谢!
【问题讨论】:
-
注解和图钉是什么关系?你怎么知道每个注释对应的是哪张图片?
-
array 中的图像与 pin 的创建顺序相同,arrayOfRestaurants 的每一项在 globalImageArray 中都有对应的项
-
因此,您需要创建自己的采用 MKAnnotation 协议的类并将图像存储在注释本身的属性中,而不是使用 MKPointAnnotation。这基本上是您链接的第二个问题中的方法
-
恐怕我不知道如何做好。您介意通过回答问题进行详细说明吗?谢谢!
标签: ios swift mkmapview mkannotation mkannotationview