我试图放置一些代表带有图像的公交车站的图钉,当我广告图像时,它会改变图钉的位置。当我没有设置图像时,图钉会掉落在正确的位置。
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is StopAnnotation {
let identifier = "stopAnnotation"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if pinView == nil {
//println("Pinview was nil")
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
pinView!.canShowCallout = true
pinView.image = UIImage(named: "stopIcon")
}
return pinView
}
return nil
}
示例
我尝试使用的图像:
谁能告诉我为什么要这样做?我在这个应用程序的 Obj-C 版本中使用完全相同的图像,一切正常。
最佳答案
代码正在使用自定义图像创建 MKPinAnnotationView
。
MKPinAnnotationView
类只能用于显示默认图钉图像。
要显示自定义图像,最好使用普通的 MKAnnotationView
。
由于代码使用 MKPinAnnotationView
,图像会自动获取应用于其的偏移量(centerOffset
属性)。
此内置偏移适用于默认图钉图像,但不适用于您的自定义图像。
不要尝试覆盖此默认行为,而是使用普通的 MKAnnotationView
来代替:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is StopAnnotation {
let identifier = "stopAnnotation"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if pinView == nil {
//println("Pinview was nil")
//Create a plain MKAnnotationView if using a custom image...
pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
pinView!.canShowCallout = true
pinView.image = UIImage(named: "stopIcon")
}
else {
//Unrelated to the image problem but...
//Update the annotation reference if re-using a view...
pinView.annotation = annotation
}
return pinView
}
return nil
}
关于ios - 将图像添加到 MKAnnotationView 会取代 pin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799174/