Passing values between ViewControllers based on list selection in Swift
Asked Answered
L

2

2

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

Luau answered 18/8, 2014 at 16:51 Comment(1)
I doubt that NSIndexPath has a property item.Silvey
A
11

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.

Allysonalma answered 19/8, 2014 at 2:0 Comment(0)
V
0

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?

Vibraharp answered 18/8, 2014 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.