Passing object with prepareForSegue Swift

后端 未结 4 1191
清歌不尽
清歌不尽 2020-12-15 06:32

I am trying to pass an object to another scene with prepareForSegue()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObj         


        
4条回答
  •  太阳男子
    2020-12-15 06:50

    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.

提交回复
热议问题