从 UITableViewCell 中的操作访问 ViewController

Access ViewController from action in TableViewCell

我有 ViewController TableView。在这个 TableView 的每个单元格中都有几个按钮(所以我不能使用 didSelectRow)。

我需要在按下按钮时从操作中获取父级 ViewController。所以我将此功能添加到我的自定义单元格 class:

@IBAction func editBtnPressed (_ sender: Any) {

}

我需要自我介绍才能向其添加一些子视图。 我怎样才能以 self 的身份访问 root ViewController?

我猜你应该通过在单元格 class 中创建你的控制器的 属性 并在 cellForRowAtIndexPath 方法中创建单元格后分配 属性 值来做到这一点。

例如:

单元格 class

weak var yourController : YourViewController?

cellForRowAtIndexPath

cell.yourController = self

然后您可以在 editBtnPressed 操作中访问 YourViewController

但我建议您在控制器中以编程方式创建按钮操作 class。这是个好方法。

例如:

class YourCellClass: UITableViewCell {
  @IBOulet var myBtn: UIbutton!
  ...
}

你的控制器class

cellForRowAtIndexPath

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! YourCellClass

    cell.myButton.addTarget(self, action: #selector(self. editBtnPressed), for: .touchUpInside)

并在 editBtnPressed

func editBtnPressed (_ sender: Any) {
 // you can access controller here by using self

}