swift - 如何在 map 上添加 2 个不同的图钉? - swift

标签 swift annotations mkmapview mkannotation mkannotationview

我试图在 map 上使用两个不同的引脚,这是我的代码:

    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
}

问题是它没有根据注释的副标题设置正确的图标。由于某种原因,有时它可以正常工作,有时却以相反的方式工作(在离线注释上设置在线图标,反之亦然)。知道为什么会发生这种情况吗?

提前致谢!

最佳答案

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

相关文章:

ios - 如何在第一首歌曲播放完毕后自动在 tableview 中播放下一首歌曲

ios - -[GMSMapView 区域] : unrecognized selector - Issue with Google Maps SDK for iOS

ios - 如何从 NSArray 在 MKMapView 中添加坐标?

swift - NSLayoutConstraint 不调整旋转 Swift 的大小

ios - Swift iOS - 如何管理多个类中不同视频的Notification.Name.AVPlayerItemDidPlayToEndTime

swift - 如何使用特定数量的计数在 SWIFT 中循环 NSTimer

Swift/Xcode - 自定义注释 View 中的按钮没有响应

java - Spring Security 中奇怪的 spring 使用

使用注释和全局拒绝的 Spring Security 白名单方法

hibernate - Hibernate 注释中的继承?