2014-07-02 41 views
14

我有一個工作循環來爲一些工作數據點的標題和字幕元素設置註釋。我想在相同的循環結構中做的事情是將引腳顏色設置爲紫色而不是默認值。我無法弄清楚是我需要做什麼來挖掘我的地圖視圖來相應地設置引腳。堅持使用Swift和MapKit中的MKPinAnnotationView()

我的工作循環,並在東西一些嘗試...

.... 
for var index = 0; index < MySupplierData.count; ++index { 

    // Establish an Annotation 
    myAnnotation = MKPointAnnotation(); 
    ... establish the coordinate,title, subtitle properties - this all works 
    self.theMapView.addAnnotation(myAnnotation) // this works great. 

    // In thinking about PinView and how to set it up I have this... 
    myPinView = MKPinAnnotationView();  
    myPinView.animatesDrop = true; 
    myPinView.pinColor = MKPinAnnotationColor.Purple; 

    // Now how do I get this view to be used for this particular Annotation in theMapView that I am iterating through??? Somehow I need to marry them or know how to replace these attributes directly without the above code for each data point added to the view 
    // It would be nice to have some kind of addPinView. 

} 

回答

35

您需要實現viewForAnnotation委託方法,並從那裏返回MKAnnotationView(或子類)。
這就像Objective-C一樣 - 底層SDK的工作方式也是一樣的。

for循環中刪除MKPinAnnotationView的創建,該循環添加註釋並實現委託方法。

這裏是viewForAnnotation委託方法在夫特一個示例實現:

func mapView(mapView: MKMapView!, 
    viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { 

    if annotation is MKUserLocation { 
     //return nil so map view draws "blue dot" for standard user location 
     return nil 
    } 

    let reuseId = "pin" 

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView 
    if pinView == nil { 
     pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     pinView!.canShowCallout = true 
     pinView!.animatesDrop = true 
     pinView!.pinColor = .Purple 
    } 
    else { 
     pinView!.annotation = annotation 
    } 

    return pinView 
} 
+0

亮 - 韓國社交協會。我放棄了這個權利,它的工作。我只是需要看到一個Swift等價物,因爲我沒有做很多Obj C.一個小問題是,編譯器在該行中使用下劃線時發出警告:func mapView(_ mapView:MKMapView!,...在paramter'mapView'中的警告是「Extraneous」_「沒有關鍵字參數名稱。 – Kokanee

+0

@Anna,你有沒有可用的示例項目?我在這裏敲我的頭在牆上感謝 – User4

+0

我沒有足夠的代表要註釋,但上面的函數仍然有效,除了pinView!.pinColor沒有折舊,它應該讀取pinView!.pinTintColor = UIColor.purpleColor() – Lunarchaos42