TableCell segue到mapkit

时间:2018-09-05 23:18:12

标签: swift

我正在尝试使用segue将注释传递给mapkit,但是当我对其进行测试时,始终会导致致命错误:意外发现nil,同时展开了可选值annotation is not a nil obj but mapView is

tableView控制器中的安全代码

if segue.identifier == "FocusOn"{
        let path = tableView.indexPathForSelectedRow
        let controller = segue.destination as! MapViewController
        let animal = animalList[(path?.row)!]
        let annotationFocus = FencedAnnotation(newTitle: animal.name!, newSubtitle: animal.animaldescription!, lat: animal.latitude, long: animal.longtitude, newType: animal.type!, newPhoto: animal.photo!)
        controller.addAnnotation(annotation: annotationFocus)
    }

}

mapview控制器中的功能

 func addAnnotation(annotation: FencedAnnotation) {
    self.mapView.addAnnotation(annotation)
    self.mapView.delegate = self
}

2 个答案:

答案 0 :(得分:1)

我认为这是因为viewDidLoad在结束之前没有被调用。

为此,请勿在您的addAnnotation中调用tableViewController,而是将注释直接发送到您的mapViewController,然后在addAnnotation或{中调用viewDidAppear {1}}。

您需要viewDidLoad

mapViewController

在您的var annotation: FencedAnnotation! 中,将注释发送到tableViewController,就像

mapViewController

然后像在let annotationFocus = FencedAnnotation(newTitle: animal.name!, newSubtitle: animal.animaldescription!, lat: animal.latitude, long: animal.longtitude, newType: animal.type!, newPhoto: animal.photo!) controller.annotation = annotationFocus 中呼叫addAnnotation

viewDidAppear

答案 1 :(得分:0)

我没有根据您的解释获得完整的图片,但我会尽力回答您。我建议在MapViewController中设置一个称为注解的变量。然后,在覆盖功能func prepare()代码中,应将该变量设置为notesFocus。这听起来可能有些混乱,但是请尝试将这段代码放入tableViewController中。

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
        if segue.identifier == "FocusOn"{
            if let controller = segue.destination as? MapViewController {
                let path = tableView.indexPathForSelectedRow
                let animal = animalList[(path?.row)!]
                let annotationFocus = FencedAnnotation(newTitle: animal.name!, newSubtitle: animal.animaldescription!, lat: animal.latitude, long: animal.longtitude, newType: animal.type!, newPhoto: animal.photo!)
                controller.annotation = annotationFocus
            }
        }
    }

然后,我将其放入您的mapViewController

    var annotation = FencedAnnotation()

    func addAnnotation() {
        self.mapView.addAnnotation(annotation)
        self.mapView.delegate = self
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        addAnnotation() 
    }

执行segue时,mapViewController中的注释将设置为注释焦点。这就是为什么在执行addAnnotation()时不需要参数。我希望这行得通。