发现检测buttoncellForRowAt

我需要检测在UITableViewController中是否点击了button

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let LikesBtn = cell.viewWithTag(7) as! UIButton } 

Swift中最简单和最有效的方法是callback闭包。

  • UITableViewCell的子类, viewWithTag标识UI元素的方法已经过时了。
  • 将自定义单元格的类设置为子类的名称,并在Interface Builder中将标识符设置为ButtonCellIdentifier

  • 添加一个callback属性。

  • 添加一个操作并将该button连接到该操作。

     class ButtonCell: UITableViewCell { var callback : (()->())? @IBAction func buttonPressed(_ sender : UIButton) { callback?() } } 
  • cellForRow将callback分配给自定义单元格。

     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellIdentifier", for: indexPath) as! ButtonCell cell.callback = { print("Button pressed", indexPath) } return cell } 
  • 当按下button时,callback被调用。 索引path被捕获。

这是我使用的:

首先将该button初始化为Outlet及其在TableViewCell

 class MainViewCell: UITableViewCell { @IBOutlet weak var testButton: UIButton! @IBAction func testBClicked(_ sender: UIButton) { let tag = sender.tag //with this you can get which button was clicked } } 

然后在你的cellForRow函数的主控制器中初始化button的标签,就像这样:

 class MainController: UIViewController, UITableViewDelegate, UITableViewDataSource, { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MainViewCell cell.testButton.tag = indexPath.row return cell } } 

第一步:为您的自定义UITableViewCell创build子类,也注册协议。

像这样的东西:

 protocol MyTableViewCellDelegate: class { func onButtonPressed(_ sender: UIButton, indexPath: IndexPath) } class MyTableViewCell: UITableViewCell { @IBOutlet var cellButton: UIButton! var cellIndexPath: IndexPath! var delegate: MyTableViewCellDelegate! override func awakeFromNib() { super.awakeFromNib() cellButton.addTarget(self, action: #selector(self.onButton(_:)), for: .touchUpInside) } func onButton(_ sender: UIButton) { delegate.onButtonPressed(sender, indexPath: cellIndexPath) } } 

在你的TableViewController中,确保它符合刚创build的协议“MyTableViewCellDelegate”。

看下面的代码,以便更好地理解。

 class MyTableViewController: UITableViewController, MyTableViewCellDelegate { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as? MyTableViewCell { cell.cellIndexPath = indexPath cell.delegate = self return cell } else { print("Something wrong. Check your cell idetifier or cell subclass") return UITableViewCell() } } func onButtonPressed(_ sender: UIButton, indexPath: IndexPath) { print("DID PRESSED BUTTON WITH TAG = \(sender.tag) AT INDEX PATH = \(indexPath)") } }