我有这个用于我的 TableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CurrentItemsCell {
cell.isUserInteractionEnabled = true
let responseItems = currentItemsArray[indexPath.row]
cell.configureCell(currentItem: responseItems)
cell.setNeedsLayout()
return cell
} else {
return CurrentItemsCell()
}
}
这是我的手机。
class CurrentItemsCell: UITableViewCell {
...
weak var mDelegate:MyProtocolImage?
...
}
@IBAction func showImages(_ sender: Any) {
guard let indexPath = indexPath else { return }
mDelegate?.sendIndexPathBack(row: indexPath.row)
print("FROM THE CELL CLASS")
}
protocol MyProtocolImage: class {
func sendIndexPathBack(row: Int)
}
在 UITableView 内部,我尝试添加 cell.mDelagate = self,但出现错误。
Cannot assign value of type 'ItemResultsViewController' to type 'MyProtocolImage?'
现在如果我做 cell.mDelegate = self as! MyProtocolImage
,语法没问题,但是应用崩溃了。
基本上,我在每个单元格内都有一个按钮,我需要获取单元格的 indexRow,这样我就可以获得按下的任何项目按钮的 itemId。然后我必须将 itemId 发送到带有 Seque 的新 ViewController(模态)。
任何帮助都会很棒
最佳答案
不要将 添加为!我的协议(protocol)图像
。相反,声明您的类符合协议(protocol)。
class ItemResultsViewController: UITableViewController, MyProtocolImage {
然后将委托(delegate)方法的实现添加到您的 ItemResultsViewController
类中:
func sendIndexPathBack(row: Int) {
// do something useful
}
现在您可以:
cell.mDelagate = self
顺便说一句 - 你的单元类中不应该有 indexPath
属性。那可以使用进一步的问题。并且您的委托(delegate)应将其自身作为参数传递给委托(delegate)方法。让委托(delegate)方法的实现者根据需要确定单元格的索引路径。永远不应告知单元格其索引路径,因为随着时间的推移它可能会出错。
更新您的细胞和协议(protocol):
@IBAction func showImages(_ sender: Any) {
mDelegate?.sendIndexPathBack(cell: self)
print("FROM THE CELL CLASS")
}
protocol MyProtocolImage: class {
func sendIndexPathBack(cell: CurrentItemsCell)
}
然后在委托(delegate)方法的实现中:
func sendIndexPathBack(cell: CurrentItemsCell) {
if let indexPath = tableView.indexPath(for: cell) {
// do something useful
}
}
关于ios - 为 UITableView Cells 设置委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261787/