I have a view controller with a table view and a separate nib for the table cell template. The cell template has some buttons. I want to access the button click along with the index of the cell clicked inside the view controller where I have defined the Table view.
So I have ViewController.h
and ViewController.m
where I have the UITableView
and TableTemplate.h
, TableTemplate.m
and TableTemplate.xib
where I have the nib defined. I want the button click event with cell index in ViewController.m
.
Any help on how can I do that?
I find it simplest to subclass the button inside your cell (Swift 3):
In your cell class:
In the table view's or collection view's data source, when dequeueing the cell, give the button its index path:
So you can just put these code into your table view controller:
And don't forget to set the button's class in your Interface Builder and link it to the
handleTapOnCellInfoButton
function!edited:
Using dependency injection. To set up calling a closure:
and inject the closure in the willDisplay method of the collection view's delegate:
Instead of playing with tags, I took different approach. Made delegate for my subclass of UITableViewCell(OptionButtonsCell) and added an indexPath var. From my button in storyboard I connected @IBAction to the OptionButtonsCell and there I send delegate method with the right indexPath to anyone interested. In cell for index path I set current indexPath and it works :)
Let the code speak for itself:
Swift 3 Xcode 8
OptionButtonsTableViewCell.swift
MyTableViewController.swift
CustomTableCell.h is a UITableViewCell:
MyVC.m after imports:
Inside "cellForRowAtIndexPath" in MyVC.m:
MyVC.m:
for swift 4:
1) In your
cellForRowAtIndexPath:
method, assign button tag as index:2) Add target and action for your button as below:
3) Code actions based on index as below in
ViewControler
:Updates for multiple Section:
You can check this link to detect button click in table view for multiple row and section.