ios – 使用prepareForSegue Swift传递对象

前端之家收集整理的这篇文章主要介绍了ios – 使用prepareForSegue Swift传递对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正试图通过prepareForSegue()将一个对象传递给另一个场景,
override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        var nextScene =  segue.destinationViewController as! VehicleDetailsTableViewController

        // Pass the selected object to the new view controller.
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let selectedVehicle = vehicles[indexPath.row]
            nextScene.currentVehicle = selectedVehicle
        }
    }

而且我有currentVehicle对象来捕捉这些对象.但是,当我尝试运行时,它会崩溃并且收到关于downcasting的错误.

编辑错误

Could not cast value of type ‘XXX.DisplayViewController’
(0x1082dcd80) to ‘XXX.VehicleDetailsTableViewController’
(0x1082dc9a0). (lldb)

解决方法

你必须在故事板中给出一个标识符(说mySegue)

使用XCode 7,swift 2.x

override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?){....}

调用为所有segues被称为形式您当前的UIViewController.所以识别者是区分不同的段落

然后使用这段代码

override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) {
    if segue.identifier == "mySegue" {
    var nextScene =  segue.destinationViewController as! VehicleDetailsTableViewController

    // Pass the selected object to the new view controller.
    if let indexPath = self.tableView.indexPathForSelectedRow {
        let selectedVehicle = vehicles[indexPath.row]
        nextScene.currentVehicle = selectedVehicle
    }
  }
}

使用Xcode 8,swift 3.x

override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    if segue.identifier == "mySegue",let nextScene = segue.destination as? VehicleDetailsTableViewController,let indexPath = self.tableView.indexPathForSelectedRow {
        let selectedVehicle = vehicles[indexPath.row]
        nextScene.currentVehicle = selectedVehicle
    }
}

在nextScene之后放置一个断点,看看它是否在单击TableView中的任何单元格时被触发.如果不是,则故事板中提供的标识符名称必须与此处给出的不同.

原文链接:https://www.f2er.com/iOS/337261.html

猜你在找的iOS相关文章