2016-05-19 71 views
0

我有以下的自定義註解類:如何在swift中添加正確的標註附件到自定義註釋?

import UIKit 
import MapKit 

class LocationMapAnnotation: NSObject, MKAnnotation { 
    var title: String? 
    var coordinate: CLLocationCoordinate2D 
    var location: Location 

    init(title: String, coordinate: CLLocationCoordinate2D, location: Location) { 
     self.title = title 
     self.coordinate = coordinate 
     self.location = location 
    } 
} 

我加載註釋成這樣的地圖視圖:

for i in 0..<allLocations.count{ 
      //Add an annotation 
      let l: Location = self.allLocations[i] as! Location 
      let coordinates = CLLocationCoordinate2DMake(l.latitude as Double, l.longitude as Double) 
      let annotation = LocationAnnotation(title: l.name, coordinate: coordinates, location: l) 
      mapView.addAnnotation(annotation) 
     } 

我如何添加一個(一)信息按鈕,地圖視圖中註釋的右側。還有一個簡單的方法來創建它的動畫?

謝謝。

+0

創建註解視圖內部按鈕,並分配給 「rightCalloutAccessoryView」 – Wolverine

+0

會有一個方法 「FUNC MapView類(MapView類:的MKMapView,viewForAnnotation註解:MKAnnotation) - ?> MKAnnotationView」它返回註解視圖。您需要在此方法中創建按鈕並按照上述步驟操作。 – Wolverine

+0

關於如何做到這一點的任何代碼?我似乎正在做這種方法出現某種錯誤。 –

回答

2

試試這個:

這裏「Sample」類實現了MKAnnotation協議。您需要根據您的註釋類型進行調整。

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

if annotation.isKindOfClass(Sample.self) { 
    if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) { 

// Reuse Annotationview 

     annotationView.annotation = annotation 
     return annotationView 
    } else { 

// Create Annotation 

     let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:identifier) 
     annotationView.enabled = true 
     annotationView.canShowCallout = true 

// Here I create the button and add in accessoryView 

     let btn = UIButton(type: .DetailDisclosure) 
     annotationView.rightCalloutAccessoryView = btn 
     return annotationView 
    } 
} 
return nil 
}