如何在viewController中为自定义UITableViewCell执行操作?

我有一个自定义单元格有一个xib,这个单元格包含一个按钮,当按下按钮时我想做一个动作,但不是在我的自定义单元格类中,而是从包含自定义单元格的tableview的viewcontroller内部,请帮助?

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

protocol CustomCellDelegate { func doAnyAction(cell:CustomUITableViewCell) } 

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

 weak var delegate:CustomCellDelegate? 

并在自定义单元类中的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. } 

现在在你的viewController中:

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

 cell.delegate = self 

3-最后在viewcontroller中调用该函数:

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

您可以使用委托模式。 创建自定义协议。

 protocol CustomTableViewCellDelegate { func buttonTapped() } 

并且在tableview单元格上符合委托

 class CustomTableViewCell: UITableViewCell { var delegate: CustomTableViewCellDelegate! @IBAction func buttonTapped(_ sender: UIButton) { delegate.buttonTapped() } } 

表视图数据源

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! CustomTableViewCell cell.delegate = self return cell } 

从表视图控制器或视图控制器符合协议(委托)

 extension TestViewController: CustomTableViewCellDelegate { func buttonTapped() { print("do something...") } } 

只需在您的cellForRowAtIndexpath获取UIButton 。 然后编写以下代码。

 button.addTarget(self, action:#selector(buttonAction(_:)), for: .touchUpInside). func buttonAction(sender: UIButton){ //... } 

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)方法添加按钮的操作。

 cell.btn.tag = indexPath.row; cell.btn.addTarget(self, action:#selector(handleButtonClicked(_:)), for: .touchUpInside). 

在视图控制器中编写选择器function:

 func handleButtonClicked(sender: UIButton){ int cellofClickedbutton = sender.tag; //... } 

在您的单元格中定义协议:

 protocol MyCellDelegate: class { func buttonTapped() } 

并定义委托变量:

 weak var delegate: MyCellDelegate? 

使您的viewController符合定义的协议。

viewController创建单元格时,为其分配委托:

 cell.delegate = self 

当点击单元格中的按钮时,发送委托相应的消息:

 delegate?.buttonTapped() 

viewController实现方法:

 func buttonTapped() { //do whatever you need } 

您可以将单元格的索引作为参数传递,因此viewController知道单击了哪个单元格按钮。