单击Pin以转到另一个ViewController

时间:2017-04-13 01:38:42

标签: ios swift mapkit

我目前有一个地图视图控制器,可以将一个引脚设置到一个位置。当点击该引脚时,我希望将其转到另一个视图控制器,但是在运行时它不会执行任何操作。有什么想法吗?

import UIKit
import MapKit

class mapquiz: UIViewController {
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let location = CLLocationCoordinate2DMake(33.5206608, -1.8913687)
        mapView.setRegion(MKCoordinateRegionMakeWithDistance(location, 1500, 1500), animated: true)

        let pin = PinAnnotation(title: "Birmingham", subtitle:"Second largest city" , coordinate: location)
        mapView.addAnnotation(pin)

        func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if(segue.identifier == "newView") {
                var UserViewController = (segue.destination as! UserViewController)
            }
        }
    }
}

2 个答案:

答案 0 :(得分:4)

使用委托方法 - didSelectAnnotationView并进行进一步操作

答案 1 :(得分:1)

MKMapViewDelegate有一个名为mapView(_:didSelect:)的方法。您可以在此方法中执行segue。此外,您应该覆盖prepare(for:sender:),而不是viewDidLoad()

import UIKit
import MapKit

class mapquiz: UIViewController {

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self

        let location = CLLocationCoordinate2DMake(33.5206608, -1.8913687)
        mapView.setRegion(MKCoordinateRegionMakeWithDistance(location, 1500, 1500), animated: true)

        let pin = PinAnnotation(title: "Birmingham", subtitle:"Second largest city" , coordinate: location)
        mapView.addAnnotation(pin)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "newView" {
            let userViewController = segue.destination as! UserViewController
            // TODO: something
        }
    }
}

extension mapquiz: MKMapViewDelegate {

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        performSegue(withIdentifier: "newView", sender: nil)
    }
}