Reputation: 2101
I'm trying to pass the selected index number of a listView selection from one ViewController to another but am running into an issue with the tableView didSelectRowAtIndexPath delegate runs slightly later than the prepareForSegue function.
Basically, in didSelectRowAtIndexPath, I seta variable, which is then picked up in the prepareForSegue. The issue is that prepareForSegue seems to run the second that the cell is selected and before the didSelectRowAtIndexPath function is called so my variable is not passed.
My main bits of code are:
tableView didSelectRowAtIndexPath delegate, which sets 'selectedResult'...
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
selectedResult = indexPath.item
txtNameSearch.resignFirstResponder() //get rid of keyboard when table touched.
println("saved result")
//tableView.deselectRowAtIndexPath(indexPath, animated: false)
//var tappedItem: ToDoItem = self.toDoItems.objectAtIndex(indexPath.row) as ToDoItem
//tappedItem.completed = !tappedItem.completed
//tableView.reloadData()
}
prepareForSegue function which sends the variable as 'toPass' to the other ViewController ('detailViewController'):
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!){
if (segue.identifier == "detailSeque") {
println("preparing")
var svc = segue!.destinationViewController as detailViewController
svc.toPass = selectedResult
//println(tableView.indexPathsForSelectedRows().
//svc.toPass = tableView.indexPathForSelectedRow()
}
}
Thanks in advance
Upvotes: 2
Views: 12820
Reputation: 154603
If you have an outlet to your tableView in your ViewController
, you can just call indexPathForSelectedRow
in prepareForSegue
.
If your ViewController
is a subclass of UITableViewController
, then you can do:
let row = self.tableView.indexPathForSelectedRow().row
println("row \(row) was selected")
If your ViewController
is not a subclass of UITableViewController
, set up an IBOutlet
to the UITableView
in your view controller:
@IBOutlet var tableView: UITableView!
and wire that up in Interface Builder and call it from prepareForSegue
as show above.
Upvotes: 11
Reputation: 4566
Instead of triggering your segue directly from a storyboard action, why don't you try programmatically calling performSegueWithIdentifier
in your didSelectRowAtIndexPath
method, after selectedResult
is set?
Upvotes: 0