Table row action to segue with indexPath row

2019-09-21 04:39发布

问题:

So I have a table view and a Custom VC. then I have an object exercises with detailImage as property. How can I get the indexPath.row from the table row action into my prepareForSegue function?

this returns nil: self.tableView.indexPathForSelectedRow

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "detailsSegue" {            
          if let indexPath = self.tableView.indexPathForSelectedRow {
             let destinationController = segue.destinationViewController as! DetailViewController
             print(self.exercises[indexPath.row].image)
             destinationController.detailImage = self.exercises[indexPath.row].image
             print ("send")
           }
    }
}

回答1:

Instead of this in your code:

if let indexPath = self.tableView.indexPathForSelectedRow {

Try this:

if let indexPath = self.tableView.indexPathForSelectedRow() {


回答2:

After playing around with the sender object in editActionsForRowAtIndexPath I got it to work. It's maybe a dirty solution but it works.

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

    let detailsAction = UITableViewRowAction(style: .Default, title: "Details", handler: {(action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
        self.performSegueWithIdentifier("detailsSegue", sender: indexPath) //sender is the indexPath
        }
    )

and then in the prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "detailsSegue" {
        let indexPath = sender!
        let destinationController = segue.destinationViewController as! DetailViewController
        print(self.exercises[indexPath.row].image)

There is probably a better way..Anyone to comment?