2

私は、地図上の2本の異なるピンを使用しようとしています、これは私が持っているコードです:Mapに2つの異なるピンを追加するには? - スウィフト

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 
} 

問題は、それが、注釈の字幕に応じて、正しいアイコンを設定していないことです。何らかの理由で時には正しく動作し、時には逆の方法で動作します(オフラインアノテーションとその逆のオンラインアイコンを設定します)。なぜこれが起きているのか?

ありがとうございます!

答えて

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 
} 
関連する問題