如何在控制器之间传递数据?
How to pass data between controllers?
我想在 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
}
}
}
这个
var cell: ParseTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as? ParseTableViewCell
正在获取一个 'new' 单元格(或者它可能正在重复使用现有的单元格),而不是从您的表格视图中获取选定的单元格。
您不应将单元格用作数据模型的替代品 - 它们只是您数据的一个视图。检索到所选单元格的 indexPath 后,只需索引到您的数组或其他数据模型即可检索您分配给 cellForRowAtIndexPath
中的单元格的图像
您正在调用 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
}
}
}
我想在 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
}
}
}
这个
var cell: ParseTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as? ParseTableViewCell
正在获取一个 'new' 单元格(或者它可能正在重复使用现有的单元格),而不是从您的表格视图中获取选定的单元格。
您不应将单元格用作数据模型的替代品 - 它们只是您数据的一个视图。检索到所选单元格的 indexPath 后,只需索引到您的数组或其他数据模型即可检索您分配给 cellForRowAtIndexPath
您正在调用 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
}
}
}