0

I am attempting to identify a cell index by the button that is pressed within the cell. After this has been done, i am trying to pass the information on to another viewController

The original post can be found here: detecting uibutton pressed in tableview: Swift Best Practices

My code currently looks like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! questionCell

    //indicates which button was pressed
    myCell.button.tag = indexPath.row
    myCell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

    return myCell
}

var selectedRow = Int()

//sets selected row variable to the row that was selected
func buttonClicked(sender:UIButton) {

    selectedRow = sender.tag
}

//sets the id of the question that was selected in the answers view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

var destinationView: AFeedTableViewController = segue.destinationViewController as! AFeedTableViewController

    destinationView.currentQuestionId = idResults[selectedRow]
}

My issue is that the prepareForSegue function is called before the buttonClicked function, and therefore no update is being made to the value i am passing on to the other view controller. Can anyone explain how to resolve this? Thanks

EDIT: When the button is clicked, a segue is performed

Community
  • 1
  • 1
rohaldb
  • 589
  • 7
  • 24

1 Answers1

1

Assuming your segue is hooked up to the button you don't need the extra target. You can reach the button via the sender object from prepareForSegue:sender:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    guard let button = sender as? UIButton else { return }
    guard let destinationViewController = segue.destinationViewController as? AFeedTableViewController else { return }

    destinationViewController.currentQuestionId = idResults[button.tag]
}
Lawree
  • 1,162
  • 1
  • 9
  • 7