How to add a button with click event on UITableViewCell in Swift?

Popular patterns for solving this problem are closures and delegates.
If you want to use closures, you would do something like this:

final class MyCell: UITableViewCell {
    var actionBlock: (() -> Void)? = nil

then

    @IBAction func didTapButton(sender: UIButton) {
        actionBlock?()
    }

then in your tableview delegate:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as? MyCell
    cell?.actionBlock = {
       //Do whatever you want to do when the button is tapped here
    }

A popular alternative is to use the delegate pattern:

    protocol MyCellDelegate: class {
        func didTapButtonInCell(_ cell: MyCell)
    }

    final class MyCell: UITableViewCell {
        weak var delegate: MyCellDelegate?

then

    @IBAction func didTapButton(sender: UIButton) {
        delegate?.didTapButtonInCell(self)
    }

..
Now in your view controller:

then in your tableview delegate:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as? MyCell
    cell?.delegate = self

And add conformance to the protocol like this:

extension MyViewController: MyCellDelegate {
    didTapButtonInCell(_ cell: MyCell) {
       //Do whatever you want to do when the button is tapped here
    }
}

Hope this helps!

Leave a Comment