Reputation: 179
I currently have a map view controller which sets a pin to a location. When clicking on the pin I would like this to go to another view controller however this does not do anything when it is ran. Any ideas?
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)
}
}
}
}
Upvotes: 0
Views: 936
Reputation: 71
Use delegate method - didSelectAnnotationView and do further manipulations
Upvotes: 4
Reputation: 2327
The MKMapViewDelegate
has a method called mapView(_:didSelect:)
. You can perform a segue in this method. Also, you should override the prepare(for:sender:)
, NOT inside the 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)
}
}
Upvotes: 1