如何在控制器之间传递数据?

时间:2015-06-07 22:22:40

标签: ios uitableview swift segue

我想在UITableViewController之间传递图片和其他数据(它有自定义UITableViewCell)。进入函数prepareForSegue我做了以下,但它不起作用。

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "identifierDetail" {
        if let index = self.tableView.indexPathForSelectedRow() {
            let controller = (segue.destinationViewController as? UINavigationController)?.topViewController as? DetailViewController

            let cellIndentifier: String = "NewsCell"

            var cell: ParseTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as? ParseTableViewCell

            controller?.image = cell?.imageViewCell.image
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您正在调用dequeueReusableCellWithIdentifier这会为您提供一个新单元格,如果您想访问该单元格中的值,您需要访问相关单元格的数据源,如下面的代码所示:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "identifierDetail" {
        if let index = self.tableView.indexPathForSelectedRow() {
            let controller = (segue.destinationViewController as? UINavigationController)?.topViewController as? DetailViewController

            let selectedData = dataSource[selectedIndexPath.row] //here dataSource is here the data to populate your table come from

            controller?.image = cell?.imageViewCell.image
        }
    }
}

答案 1 :(得分:0)

这个

var cell: ParseTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as? ParseTableViewCell

正在获得一个新的'单元格(或者它可能正在重用现有单元格),而不是从您的tableview中获取所选单元格。

您不应该使用单元格作为数据模型的替代方案 - 它们只是数据的视图。检索到所选单元格的indexPath后,只需索引到数组或其他数据模型,即可检索分配给cellForRowAtIndexPath

中单元格的图像。
相关问题