我们如何将选定的注释打印到控制台?

How could we print selected annotation to console?

我是 swift 的新手,这里有一个通过长手势触摸添加注释的解决方案,我们如何将选定的注释打印到控制台?

Swift 4

import UIKit
import MapKit

class MapViewController: UIViewController , MKMapViewDelegate {

    @IBOutlet weak var mapView : MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()


    let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.handleTap(_:)))
    longPressRecogniser.minimumPressDuration = 1.0
    mapView.addGestureRecognizer(longPressRecogniser)

    mapView.mapType = MKMapType.standard

    let location = CLLocationCoordinate2D(latitude: 23.0225,longitude: 72.5714)

    let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    let region = MKCoordinateRegion(center: location, span: span)
    mapView.setRegion(region, animated: true)

    let annotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "iOSDevCenter-Kirit Modi"
    annotation.subtitle = "Ahmedabad"
    mapView.addAnnotation(annotation)
}

这里是添加注释的函数:

    @objc func handleTap(_ gestureReconizer: UILongPressGestureRecognizer)
{

    let location = gestureReconizer.location(in: mapView)
    let coordinate = mapView.convert(location,toCoordinateFrom: mapView)

    // Add annotation:
    let annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    mapView.addAnnotation(annotation)
}

您可以使用mapView:didSelect方法。

例如

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("selected annotation", view.annotation)
    print("selected annotation", view.annotation?.title)
    print("selected annotation", view.annotation?.coordinate)
}

不要忘记在 viewDidLoad 中设置 mapView.delegate = self