zach2161 zach2161 - 5 months ago 13
Swift Question

Bad Exception on swipe action cell Swift

I'm making an app that is sending information about text inside of cells to a WebViewController using swipe actions. The swipe action is:

let sendToWebsite = UITableViewRowAction(style: .Default, title: "Website")
{ (action, indexPath) in
self.performSegueWithIdentifier("yourSegueIdentifier", sender: nil)
}
sendToWebsite.backgroundColor = UIColor.blueColor()
return [sendToWebsite]
}


This works fine but I also have two segues coming from the same View Controller, to two other VC's. The first segue(recipeDetail) is when you tap directly on the cell and works fine, but the second segue(yourSegueIdentifier) is a button that appears when you activate the slide action on the cell and does't work. Cell Swipe Action

the segues:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "recipeDetail") {
let indexPath = self.tableView!.indexPathForSelectedRow
let destinationViewController: DetailViewController = segue.destinationViewController as! DetailViewController

destinationViewController.recipe = recipes[indexPath!.row]
}
else if segue.identifier == "yourSegueIdentifier"
{
let indexPath = self.tableView!.indexPathForSelectedRow
let nextVC: WebViewController = segue.destinationViewController as! WebViewController

nextVC.recipe = recipes[indexPath!.row]
}
}


On the line

nextVC.recipe = recipes[indexPath!.row]


indexPath is coming out as nil and giving the following error message
error on line 13

Answer

Well it looks like on the swipe action, the tableView doesn't register the "indexPathForSelectedRow" method. What you could alternatively do is setup a global swipeIndex variable

class ViewController: UIViewController{

var swipeIndex : Int!
//Code, code, code...

and then set it once the swipe action is called.

let sendToWebsite = UITableViewRowAction(style: .Default, title: "Website")
{ (action, indexPath) in
    self.swipeIndex = indexPath.row
    self.performSegueWithIdentifier("yourSegueIdentifier", sender: nil)
}
    sendToWebsite.backgroundColor = UIColor.blueColor()
    return [sendToWebsite]
}

and then:

else if segue.identifier == "yourSegueIdentifier"
    {
        let indexPath = self.tableView!.indexPathForSelectedRow
        let nextVC: WebViewController = segue.destinationViewController as! WebViewController

        nextVC.recipe = recipies[self.swipeIndex]
    }
}