How can I detect which Button in a table cell was pressed?

I want to use the indexPath.row from my table view to serach for an element in an array in an other function when the button is pressed.

My first idea was to add an action for the button, but i can´t use a parameter using addTarget.


I read something about to create for every button a new tag, but i have no idea how to do it.

Answered by Batdoctor in 259410022

Ok i got it:D

Here is my solution:


In cellForRowAt indexPath:

cell.button.addTarget(self, action: #selector(whichButtonPressed(sender:)), for: .touchUpInside)


func whichButtonPressed(sender: UIButton) {

var buttonNumber = sender.tag

}


This works fine:)

Implement the protocol UITableViewDelegate & the following method, remove the button, the table view touch will trigger the method below ...


func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

}

This was also one idea and it works, but i really need to use a button in the tableView cell.

not sure I understand your question, but...


when you load the cell, you could set the tag of the button with the row.


then in the button action, use the tag to get the row value back.

Accepted Answer

Ok i got it:D

Here is my solution:


In cellForRowAt indexPath:

cell.button.addTarget(self, action: #selector(whichButtonPressed(sender:)), for: .touchUpInside)


func whichButtonPressed(sender: UIButton) {

var buttonNumber = sender.tag

}


This works fine:)

How can I detect which Button in a table cell was pressed?
 
 
Q