如何对我的viewController中的自定义UITableViewCell执行操作? [英] How to perform action for a custom UITableViewCell inside my viewController?

查看:67
本文介绍了如何对我的viewController中的自定义UITableViewCell执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom cell that has a xib, this cell contains a button, when the button is pressed I want to do an action , but not inside my custom cell class but from inside the viewcontroller that contains the tableview of the custom cell, any help please?

推荐答案

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

First of all you should write a protocol for example:

protocol CustomCellDelegate {
  func doAnyAction(cell:CustomUITableViewCell)
}

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

Then inside your custom cell class declare:

weak var delegate:CustomCellDelegate?

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

and inside your IBAction in the custom cell class:

@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中:

Now in your viewController:

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

1- Make your view controller implement CustomCellDelegate. 2- In your cellForRow when declaring the cell don't forget to write:

cell.delegate = self

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

3- Finally call the function in your viewcontroller:

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

    }
}

这篇关于如何对我的viewController中的自定义UITableViewCell执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆