2016-12-02 13 views
0

2つの注釈を持つ地図があり、それぞれに2つの異なる画像が必要です。SwiftでMKAnnotationに画像を変更するには

私は1つの注釈でそれを行う方法を知っていますが、私の問題は2つの注釈です。

は、ここに1つのために私のコードです:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
     let reuseId = "pin" 

     var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 


     anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     anView!.image = nil; 
     anView!.image = UIImage(named:"destinationPin") 


     return anView 

    } 

そして、あなたはreuseIdあるものを私に説明している場合、誰もが、私は本当に感謝することができた場合

。事前に

おかげ

+0

2つのアノテーションをどういう意味ですか? 2つの別々のクラス? – sdasdadas

+0

私はマップ上に2つのピンを持っていて、それらのそれぞれに別のイメージを持たせたいと思っています。 –

答えて

1

まず、マップに注釈を追加するとき、あなたがそれらを区別する必要があります。簡単な方法は、タグの値を設定することです。あなたのロジックを分岐するために使用することができ

if annotation.tag == 0 { 
    anView!.image = UIImage(named:"destinationPin") 
} else { 
    anView!.image = UIImage(named:"alternateDestinationPin") 
} 

注MKAnnotationは、タイトルのような他の特性を有し、その座標:そして、あなたは次のようにあなたのロジックを分岐することができます。

+0

答えをありがとう私はできるだけ早くそれをチェックしてお知らせします –

+0

私はタイトルを使用しました。私はあなたが何か一般的なものとしてタグを入れていると思いますか? (注釈にメンバータグがないというエラーが返されたため) –

+0

はい。現在のプロジェクトでは、adasdadasのようにサブクラス化し、タグ値を追加しました。私は答えを投稿したときに私はそれを忘れた –

0

オプションとしてキャストすることができます。

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
    let reuseId = "pin" 

    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 

    if let annotation1 = anView as? FirstAnnotation { 
     annotation1.image = UIImage(named: "first.jpg") 
    } else if let annotation2 = anView as? SecondAnnotation { 
     annotation2.image = UIImage(named: "second.jpg") 
    } 
    return anView 
} 

この追加型の安全性の利益とtag内部にある何の自分自身の知識に頼らないを持っています。 2つの別々のタイプのMKAnnotationがある場合は、それらを実際には2つの個別のクラスとしてサブクラス化する必要があります。

関連する問題