Send variable value to next view controller when click a table cell

余生颓废 提交于 2019-12-08 05:37:52

问题


I have two table view controllers

  1. InvoiceList view controller
  2. InvoiceShow view controller

I use didSelectRowAtIndexPath method as bellow to get selected table cell specific value

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     let rowObject = objects[indexPath.row]
     let invoicehash = rowObject["hash_key"]!
}

i need to send invoicehash value to InvoiceShow controller when click the table cell of InvoiceList

i tried to use prepareForSegue function. but it is not applicable because it will trigger before the didSelectRawAtIndexPath function. so when i implemented it, gives the previous click event variable value. not correct one.

Please help me to access invoiceHash variable value from InvoiceShow controller


回答1:


You will get the selected cell in prepareForSegue method itself.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  let selectedIndexPath = self.tableView.indexPathForSelectedRow()!

  let rowObject = objects[selectedIndexPath.row]
  let invoiceHash = rowObject["hash_key"]!

  let invoiceShowViewController = segue.destinationViewController as! InvoiceShowViewController

  // Set invoiceHash to `InvoiceShowViewController ` here
  invoiceShowViewController.invoiceHash = invoiceHash
}



回答2:


You can still use a segue if you want and/or already setup on your storyboard. You just need to connect the two view controllers in Interface Builder directly from one to another. So, start ctrl-dragging from the controller itself and not from the TableViewCell (take a look at the screenshot)

then use the performSegueMethod with the new segue identifier like this:

self.performSegueWithIdentifier("mySegueIdentifier", sender: self)

and finally, your prepareForSegue method:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "mySegueIdentifier" {
        let selectedIndex = self.invoiceTableView.indexPathForSelectedRow
        //if element exist
        if selectedIndex?.row < myDataSourceArray.count {
            let destination = segue.destinationViewController as! InvoiceShowViewController
            let invoice = myDataSourceArray[selectedIndex!.row]
            destination.invoice = invoice
        }
    }
}

That's it!



来源:https://stackoverflow.com/questions/33658844/send-variable-value-to-next-view-controller-when-click-a-table-cell

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