I need to detect if the button has been clicked in the UITableViewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let LikesBtn = cell.viewWithTag(7) as! UIButton
}
I need to detect if the button has been clicked in the UITableViewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let LikesBtn = cell.viewWithTag(7) as! UIButton
}
Here is what I use:
First initialize the button as an
Outlet
and itsaction
on yourTableViewCell
Then in you Main Controller in the cellForRow function just initialize the tag of the button like this:
First step: Make Subclass for your custom UITableViewCell, also register protocol.
Something like this:
In your TableViewController, make sure it conform to your just created protocol "MyTableViewCellDelegate".
Look at the code below for better understanding.
The easiest and most efficient way in Swift is a callback closure.
UITableViewCell
, the viewWithTag way to identify UI elements is outdated.Set the class of the custom cell to the name of the subclass and set the identifier to
ButtonCellIdentifier
in Interface Builder.Add a
callback
property.Add an action and connect the button to the action.
In
cellForRow
assign the callback to the custom cell.When the button is pressed the callback is called. The index path is captured.
Edit
There is a caveat if cells can be added or removed. In this case update the index path by getting the current index from the data source array
If even the
section
can change, well, then protocol/delegate may be more efficient.