通过点击添加userlocation注释

时间:2016-01-11 19:45:39

标签: ios swift

如果点击按钮,如何为mapView添加注释?注释位于用户位置。

我的代码将成功运行,但当您点按按钮addAnnotation时,应用程序将崩溃。它说:

  

致命错误:在解包可选值时意外发现nil

var myLocation : CLLocation!

    @IBAction func addAnnotation(sender: UIBarButtonItem) {

            let center = CLLocationCoordinate2D(latitude: myLocation.coordinate.latitude, longitude: myLocation.coordinate.longitude)
            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

            self.mapView.setRegion(region, animated: true)

        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            self.myLocation = locations.last as CLLocation!
        }

        let addPin = MKPointAnnotation()
        addPin.coordinate = center
        addPin.title = "ENDELIG!"
        self.mapView.addAnnotation(addPin)
    }
}

0 个答案:

没有答案