UIButton action in table view cell UIButton action in table view cell ios ios

UIButton action in table view cell


Swift 4 & Swift 5:

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

@objc func connected(sender: UIButton){    let buttonTag = sender.tag}


The accepted answer using button.tag as information carrier which button has actually been pressed is solid and widely accepted but rather limited since a tag can only hold Ints.

You can make use of Swift's awesome closure-capabilities to have greater flexibility and cleaner code.

I recommend this article: How to properly do buttons in table view cells using Swift closures by Jure Zove.

Applied to your problem:

  1. Declare a variable that can hold a closure in your tableview cell like

    var buttonTappedAction : ((UITableViewCell) -> Void)?
  2. Add an action when the button is pressed that only executes the closure. You did it programmatically with cell.yes.targetForAction("connected", withSender: self) but I would prefer an @IBAction outlet :-)

    @IBAction func buttonTap(sender: AnyObject) {   tapAction?(self)}
  3. Now pass the content of func connected(sender: UIButton!) { ... } as a closure to cell.tapAction = {<closure content here...>}. Please refer to the article for a more precise explanation and please don't forget to break reference cycles when capturing variables from the environment.


Simple and easy way to detect button event and perform some action

class youCell: UITableViewCell{    var yourobj : (() -> Void)? = nil    //You can pass any kind data also.   //var user: ((String?) -> Void)? = nil     override func awakeFromNib()        {        super.awakeFromNib()        } @IBAction func btnAction(sender: UIButton)    {        if let btnAction = self.yourobj        {            btnAction()          //  user!("pass string")        }    }}func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell    {        let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell        cell?.selectionStyle = UITableViewCellSelectionStyle.Nonecell!. yourobj =            {                //Do whatever you want to do when the button is tapped here                self.view.addSubview(self.someotherView)        }cell.user = { string in            print(string)        }return cell}