MKMapView setregion swift

961 views Asked by At

I have a MKMapView initiated in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
        .....
        let mapView = MKMapView(frame: view.bounds)
        mapView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
        mapView.delegate = self
        view.addSubview(mapView)
        view.sendSubviewToBack(mapView)

and a button:

@IBAction func findMePressed(sender: AnyObject) {
     .....
    mapView.setRegion(reg, animated: true)
}

I understand the button isn't working because the MKMapView is declared in the viewDidLoad. It works fine in another view where it's linked with the storyboard. But in this view I have to initialise it like this because of custom annotations won't work with me for some reason. How could I link the button to the viewDidLoad initialiser

1

There are 1 answers

0
zisoft On

You declared your mapView as a local variable hence it is only in scope in the viewDidLoad method.

Make your mapView an instance variable of the viewController:

class MapViewController: UIViewController, MKMapViewDelegate {
    var mapView: MKMapView

    override func viewDidLoad() {
        super.viewDidLoad()
            .....
        self.mapView = MKMapView(frame: view.bounds)
        self.mapView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
        self.mapView.delegate = self
        view.addSubview(self.mapView)
        view.sendSubviewToBack(self.mapView)
    }

    ...

    @IBAction func findMePressed(sender: AnyObject) {
        .....
        self.mapView.setRegion(reg, animated: true)
    }

}