Passing values between ViewControllers based on list selection in Swift

爱⌒轻易说出口 提交于 2019-12-12 17:24:30

问题


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


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/25368245/passing-values-between-viewcontrollers-based-on-list-selection-in-swift

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