How to update selected row before segue?

余生颓废 提交于 2019-12-13 21:35:51

问题


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?


回答1:


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.




回答2:


in your prepareForSegue:

 controller.activeCourse = self.tableView.indexPathForSelectedRow

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




回答3:


Use this on prepareForSegue:

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

or

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


来源:https://stackoverflow.com/questions/34109152/how-to-update-selected-row-before-segue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!