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

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!


All patterns above are fine.my two cents, in case You add by code (for example multiple different cells and so on..)there is a FAR simple solution.

As buttons allow to specify a "target" You can pass directly the controller AND action to cell/button when setting it.

In controller:

let selector = #selector(self.myBtnAction)setupCellWith(target: self, selector: selector)

...

in custom cell with button:

final func setupCellWith(target: Any? selector: Selector){       btn.addTarget(target,         action: selector,       for: .touchUpInside)}


2 am answer: You're over thinking this. Create a custom TableViewCell class; set the prototype cell class to your new custom class; and then create an IBAction.