2016-12-02 20 views
0

我有一張帶有2個註釋的地圖,並且我需要2個不同的圖像給他們每個人。如何使用Swift將圖像更改爲MKAnnotation

我知道如何做一個註釋,但我的問題是有兩個註釋。

這裏是我的代碼之一:

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

你是什麼意思兩個註釋?兩個單獨的課程? – sdasdadas

+0

我在地圖上有兩個針,我希望他們每個人都有不同的圖像 –

回答

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知識。如果你有兩個單獨的MKAnnotation類型,你應該將它們分類爲兩個單獨的類。

相關問題