Jesús Guerrero Almaraz Jesús Guerrero Almaraz - 5 months ago 61
Swift Question

How to send didSelectRowAtIndexPath back to view controller in swift

I have 1 viewController and 1 tableViewController in swift. I can send an NSMutableArray from the viewController to populate the tableViewController using segue. I do not know how to send the selected row back to the view controller. The code so far:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")

// Missing code for sending back the selected row

self.dismissViewControllerAnimated(true, completion: nil)
}


Any ideas?

Answer

You can use the delegation pattern. Create a protocol:

protocol MyDataDelegate {
    didSelectRow(row: NSIndexPath, data: MyData)
}

In the table controller, add a property:

var myDataDelegate: MyDataDelegate?

and in the didSelectRowAtIndexPath call the delegate method:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println("You selected cell #\(indexPath.row)!")

    let data = getDataForRow(indexPath) // <== You need to implement it
    self.myDataDelegate?.didSelectRow(indexPath, data: data)

    self.dismissViewControllerAnimated(true, completion: nil)
}

Next, in your main view controller:

  • implement the MyDataDelegate protocol
  • implement the MyDataDelegate.didSelectRow method
  • right before presenting the table controller (or after creating it, if you manually do it), set the myDataDelegate property of the table controller to self

This way, when a row is selected in your table controller, the didSelectRow method is called on your main view controller, so you can do whatever you need with the index path and/or the data.

Of course feel free to change the didSelectRow signature (use the indexpath, or a row index, with or without data, etc.)

Comments