在选择时从自定义 UITableViewCell 中检索对象

Retrieve object from custom UITableViewCell on selection

所以我有一个填充了自定义 UITableViewCell 的 UITableView。每个单元格都加载了一个我想在行选择时检索的对象。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Here I would like to retrieve the object associated with the selected row.

// Object "cell" is inferred as a UITableViewCell, not as CustomTableViewCell :(
var cell = myTableView.cellForRowAtIndexPath(indexPath)

}

如上所述,我无法访问 CustomTableViewCell 以获取关联对象。还有其他方法吗?

您应该将其转换为 CustomTableViewCell,试试看:

var cell = myTableView.cellForRowAtIndexPath(indexPath) as CustomTableViewCell

您必须键入您在构造 cell.

时使用的 class
let cell = myTableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

let cell = myTableView.cellForRowAtIndexPath(indexPath) as MyTableViewCellClass

通常,您的 UITableView 由数据源备份,例如数组。因此,使用提供的 indexPath 从数组中获取对象。

除此之外,您还可以将单元格转换为自定义 class:

var cell = myTableView.cellForRowAtIndexPath(indexPath) as CustomTableViewCell