Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

ios - Passing object with prepareForSegue Swift

I am trying to pass an object to another scene with 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
        }
    }

And I have currentVehicle object to catch these object. But, when I try to run, it brokes and get error about downcasting.

Error EDIT

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to give the segue an identifier in the storyboard.(say mySegue)

Using Xcode 10 swift 4.x(Also works with Xcode 9 & 8 , swift 3.x)

override func prepare(for segue: UIStoryboardSegue, sender: Any?){}

Is called for all segues being called from your current UIViewController. So the identifier is to differentiate the different segues

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
    }
}

If you are using Using Xcode 7, swift 2.x

Then use this code:

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
    }
  }
}

Place a breakpoint after nextScene and see if it is being triggered by clicking any cell in the TableView. If it isn't then the identifier name u provided in the storyboard must be different then the one given here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...