2014-10-07 37 views

回答

8

您必須創建一個派生自MKMapView的自定義類。該課程必須實施MKMapViewDelegate協議。

然後您需要2個步驟:創建註釋對象併爲該註釋創建一個視圖。

創建註釋:

某處在你的代碼,取決於你的需要:

let annotation = MKPointAnnotation() 
annotation.setCoordinate(location) // your location here 
annotation.title = "My Title" 
annotation.subtitle = "My Subtitle" 

self.mapView.addAnnotation(annotation) 

創建註釋視圖

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { 
    if annotation is MKPointAnnotation { 
     let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin") 

     pinAnnotationView.pinColor = .Purple 
     pinAnnotationView.draggable = true 
     pinAnnotationView.canShowCallout = true 
     pinAnnotationView.animatesDrop = true 

     return pinAnnotationView 
    } 

    return nil 
} 
+0

非常感謝! :D – 2014-10-07 15:17:18

4

這是我的示例代碼。此代碼允許您長按地圖添加一個點並拖動該點,直到您從屏幕上釋放手指。還要看看您必須在地圖視圖中添加的gestureRecognizer。希望這可以幫助你。

class TravelLocationMapController: UIViewController, MKMapViewDelegate { 


@IBOutlet var mapView: MKMapView! 

var dragPin: MKPointAnnotation! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    mapView.delegate = self 
    let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: "addPin:") 
    gestureRecognizer.numberOfTouchesRequired = 1 

    mapView.addGestureRecognizer(gestureRecognizer) 
} 

func addPin(gestureRecognizer:UIGestureRecognizer){ 
    let touchPoint = gestureRecognizer.locationInView(mapView) 
    let newCoordinates = mapView.convertPoint(touchPoint, toCoordinateFromView: mapView) 
    if dragPin != nil { 
     dragPin.coordinate = newCoordinates 
    } 

    if gestureRecognizer.state == UIGestureRecognizerState.Began { 
     dragPin = MKPointAnnotation() 
     dragPin.coordinate = newCoordinates 
     mapView.addAnnotation(dragPin) 
    } else if gestureRecognizer.state == UIGestureRecognizerState.Ended {    
     dragPin = nil 
    } 
} 

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
    if annotation is MKPointAnnotation { 
     let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin") 

     pinAnnotationView.pinTintColor = UIColor.purpleColor() 
     pinAnnotationView.animatesDrop = true 

     return pinAnnotationView 
    } 
    return nil 
} 

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { 
    let lat = view.annotation?.coordinate.latitude 
    let long = view.annotation?.coordinate.longitude 

    print("Clic pin lat \(lat) long \(long)") 

} 
+0

超級,謝謝!儘管如此,你應該嘗試在''mapView(_:viewForAnnotation)''中用''mapView.dequeueReusableAnnotationViewWithIdentifier(「myPin」)''來獲得現有的MKPinAnnotationView''。 – brki 2015-12-01 14:00:50

相關問題