如何对我的viewController中的自定义UITableViewCell执行操作?

3 iphone ios swift swift3 ios10

我有一个具有xib的自定义单元格,该单元格包含一个按钮,当按下按钮时,我想执行一个操作,但不是在我的自定义单元格类内部,而是从包含自定义单元格的viewviewler的内部请帮忙?

Jaa*_*rek 5

首先,您应该编写一个协议,例如:

protocol CustomCellDelegate {
  func doAnyAction(cell:CustomUITableViewCell)
}
Run Code Online (Sandbox Code Playgroud)

然后在您的自定义单元格类中声明:

weak var delegate:CustomCellDelegate?
Run Code Online (Sandbox Code Playgroud)

并在自定义单元类的IBAction中:

@IBAction func onButtonTapped(_ sender: UIButton) {
    delegate?.doAnyAction(cell: self)
 //here we say that the responsible class for this action is the one that implements this delegate and we pass the custom cell to it.
}
Run Code Online (Sandbox Code Playgroud)

现在在您的viewController中:

1-使您的视图控制器实现CustomCellDelegate。2-在您的cellForRow声明单元格时,不要忘了写:

cell.delegate = self
Run Code Online (Sandbox Code Playgroud)

3-最后在您的ViewController中调用该函数:

func doAnyAction(cell: CustomUITableViewCell) {
    let row = cell.indexPath(for: cell)?.row
  //do whatever you want

    }
}
Run Code Online (Sandbox Code Playgroud)