ios - 为 UITableView Cells 设置委托(delegate)

标签 ios swift uitableview

我有这个用于我的 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/

相关文章:

ios - 使用私有(private)框架 BluetoothManager/iOS 5.0

ios - UIImageView 未在 3,5 屏幕上完全显示

来自服务器的 iOS tcp 套接字 json

ios - 如何在 iOS Swift 中实时录制音频声音,然后使用内置扬声器或耳机播放?

ios - 无法在 Xcode 7.2 上使用 Swift 在设备上构建(与供应配置文件无关)

iphone - 如何使用 swift 更改 UICell 上字母和线条之间的间距

UITableView 内容高度

android - React Native 迁移 - FaSTLane 构建仅在 CircleCI 上针对 iOS "Archive failed"失败

swift - 将类 "hides"的 UITableView 设置为 outlets 的 outlet 部分

ios - UITableViewController : "Popovers cannot be presented from a view which does not have a window. "