MKMapView setregion swift

时间:2015-06-15 08:46:14

标签: swift mkmapview

我在viewDidLoad中启动了一个MKMapView:

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

和一个按钮:

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

我理解该按钮不起作用,因为MKMapView是在viewDidLoad中声明的。它在另一个与故事板链接的视图中工作正常。但是在这种观点中我必须像这样初始化它,因为自定义注释由于某种原因而不能与我合作。如何将按钮链接到viewDidLoad初始化程序

1 个答案:

答案 0 :(得分:1)

您将mapView声明为局部变量,因此它仅在viewDidLoad方法的范围内。

使mapView成为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)
    }

}