我试图在地图上使用两个不同的别针,这是我拥有的代码:

    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
}

问题是它没有根据批注的副标题设置正确的图标。出于某种原因,它有时工作正常,有时工作方式相反(在脱机注释和viceversa上设置联机图标)。知道为什么会这样吗?.
事先谢谢!

最佳答案

因为您忘记更新已排队注释视图的.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
}

关于swift - 如何在 map 上添加2个不同的引脚? - swift ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42800774/

10-08 20:49