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?
Swift 3 with a Closure
A nice solution is using a closure in a custom UITableViewCell to callback to the viewController for an action.
In cell:
In View Controller: Tableview Delegate
Use Swift closures :
Its Work For me.
@Mani answer is good, however tags of views inside cell's contentView often are used for other purposes. You can use cell's tag instead (or cell's contentView tag):
1) In your
cellForRowAtIndexPath:
method, assign cell's tag as index:2) Add target and action for your button as below:
3) Create method that returns row of the sender (thanks @Stenio Ferreira):
4) Code actions based on index:
Tarun's code doesnt work on iOS7, since the UITableViewCell structure changed and now he would get "UITableViewCellScrollView" instead.
This post Getting UITableViewCell with superview in iOS 7 has a good solution creating a loop to find the correct parent view, regardless of any future changes in the structure. It boils down to creating a loop:
The link has code for a more reusable solution, but this should work.