我想在地图上使用两个不同的引脚,这是我的代码:
func mapView (_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
//avoid for user location
if (annotation is MKUserLocation) {
return nil
}
let reuseId = "annId"
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if anView == nil {
if(annotation.subtitle! == "Offline"){
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView!.image = UIImage(named:"offIceCream.pdf")!
anView!.canShowCallout = true
}
if(annotation.subtitle! == "Online"){
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView!.image = UIImage(named:"onIceCream.pdf")!
anView!.canShowCallout = true
}
} else {
anView!.annotation = annotation
}
return anView
}
问题在于它没有根据注释的字幕设置正确的图标。出于某种原因,有时它可以正常工作,有时它的工作方式相反(在离线注释上设置在线图标,反之亦然)。知道为什么会这样吗?。
提前致谢!
答案 0 :(得分:1)
因为您忘记更新已经排队的注释视图的.image
:
if anView == nil {
...
}
else {
anView!.annotation = annotation
if (annotation.subtitle! == "Offline") {
anView!.image = UIImage(named:"offIceCream.pdf")!
}
else if (annotation.subtitle! == "Online") {
anView!.image = UIImage(named:"onIceCream.pdf")!
}
}
编写整个逻辑的更清晰的方法是:
func mapView (_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
if (annotation is MKUserLocation) {
return nil
}
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: "annId")
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: "annId")
}
else {
anView?.annotation = annotation
}
anView?.canShowCallout = true
if (annotation.subtitle! == "Offline") {
anView?.image = UIImage(named: "offIceCream.pdf")
}
else if (annotation.subtitle! == "Online") {
anView?.image = UIImage(named: "onIceCream.pdf")
}
return anView
}