Passing values between ViewControllers based on list selection in Swift

12,759

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.

Share:
12,759

Related videos on Youtube

Oliver Spencer
Author by

Oliver Spencer

Updated on June 05, 2022

Comments

  • Oliver Spencer
    Oliver Spencer almost 2 years

    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