在Swift 3中按下MKPointAnnotation时如何调用函数

时间:2018-06-24 18:09:17

标签: ios swift mapkit

我一直在尝试一切以获取注释来快速调用函数的方法。我不知道我做错了什么,但那根本行不通。 我曾尝试在真正的iPhone上测试我的项目,但也没有任何反应。

这是我的代码:

import UIKit
import MapKit
import Foundation
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

//Map

@IBOutlet weak var map: MKMapView!

let manager = CLLocationManager()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let location = locations[0]

    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
    map.setRegion(region, animated: true)

    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "coffee"

    // Set the region to an associated map view's region
    request.region = map.region

    let search = MKLocalSearch(request: request)
    search.start { response, error in
        guard let response = response else {
            print("There was an error searching for: \(String(describing: request.naturalLanguageQuery)) error: \(String(describing: error))")
            return
        }

        for item in response.mapItems
        {
            print("URL=\(String(describing: item.url ?? nil))")
            print("Name=\(String(describing: item.name ?? nil))")
            print("Phone Number\(String(describing: item.phoneNumber ?? nil))")


            let annotation = MKPointAnnotation()
            annotation.coordinate = item.placemark.coordinate
            annotation.title = item.name
            self.map.addAnnotation(annotation)
        }
    }
    self.map.showsUserLocation = true
}


override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()
}

func callThisFunction() {
    print("The function has been called.")
}

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    callThisFunction()
}

我看了很多有关如何执行此操作的文章,但我不太了解。谢谢,敬请谅解。

1 个答案:

答案 0 :(得分:1)

添加

map.delegate = self

到您的viewDidLoad()

哦,Xcode告诉我

  

实例方法“ mapView(mapView:didSelectAnnotationView :)”几乎与协议“ MKMapViewDelegate”的可选要求“ mapView(_:didSelect :)”相匹配

您也应该使用“修复”按钮修复该问题。