Chandler Freeman
Chandler Freeman

Reputation: 899

How to update selected row before segue?

I need to pass a variable containing the index of the selected row in one view to the next view.

firstview.swift

var selectedRow = 0;

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        selectedRow = indexPath.row + 1
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "viewAssignmentsSegue") {
            let navController = segue.destinationViewController as! UINavigationController
            let controller = navController.viewControllers[0] as! AssignmentsViewController
            print(selectedRow)
            controller.activeCourse = selectedRow
        }
    }

My issue is that, when a row is selected, the selectedRow variable isn't updated by the tableView method before the segue occurs, meaning that the value is essentially always one behind what it should be. How can I delay the prepareForSegue until the variable is updated or how else can I successfully pass the selected row to the next view without delay?

Upvotes: 0

Views: 166

Answers (3)

Claudio Castro
Claudio Castro

Reputation: 1569

Use this on prepareForSegue:

        let path = self.tableView.indexPathForSelectedRow()!
        controller.activeCourse = path.row

or

        let path = self.tableView.indexPathForCell(sender)
        controller.activeCourse = path.row

Upvotes: 0

Daij-Djan
Daij-Djan

Reputation: 50089

in your prepareForSegue:

 controller.activeCourse = self.tableView.indexPathForSelectedRow

don't wait for didSelect to be called - react earlier.

Upvotes: 0

matt
matt

Reputation: 535202

One possibility: Don't implement didSelectRowAtIndexPath:. Just move that functionality into your prepareForSegue implementation. That, after all, is what is called first in response to your tapping the cell. Even in prepareForSegue you can ask the table view what row is selected.

Another possibility: Implement willSelectRowAtIndexPath: instead of didSelectRowAtIndexPath:. It happens earlier.

Upvotes: 1

Related Questions