Hi I have a custom UITableViewCell with three buttons to handle a shopping cart function, Plus,Minus and Delete button and I need to know which cell has been touched.
I've already tried to use the "tag solution" but it isn't working due to the lifecycle of the cells.
Can anyone please help me find a solution?
Thanks in advance
You can also get selected button index using tableViewCell view's hierarchy.
Using following steps :
add selector to the cellForRowAtIndexpath of tableview :
2 . get indexPath using following method :
@pedrouan is great, except using button's
tag
option. In many cases, when you set button ontableViewCell
, those buttons will modify tableView dataSource.(e.g. InsertRow, DeleteRow).But the tag of the button is not updated even if a new cell is
inserted
ordeleted
. Therefore, it is better to pass thecell
itself as a parameter rather than passing the button'stag
to the parameter.Here is my example to achieve this.
Your
ExampleCell
Your
ViewController
I was resolving this using a cell delegate method within UITableViewCell's subclass.
Quick overview:
1) Create a protocol
2) Subclass your
UITableViewCell
(if you haven't done so):3) Let your view controller conform to
YourCellDelegate
protocol that was implemented above.4) Set a delegate, after the cell has been defined (for reusing).
5) In the same controller (where is your implemented UITableView delegate/datasource), put a method from
YourCellDelegate
protocol.Now, your solution is not tag / number dependent. You can add as many buttons as you want, so you are ready to get response via delegate regardless how many buttons you want to install.
This protocol-delegate solution is preferred in iOS logic and it can be used for other elements in table cell, like
UISwitch
,UIStepper
, and so on.I came across the same problem after making the IBOutlets private as has been broadly suggested by the community.
Here is my solution:
< In your cell class >
< In your ViewController >
SWIFT 4.*
It can be done like following way too, Not required much coding and delegation, Simple and easy.
Put following code in
cellForItemAt
forUICollectionView
or incellForRowAt
forUITableView
And your Method will be
Thats all.