ankit_rck ankit_rck - 4 months ago 83
iOS Question

Get button click inside UI table view cell

I have a ViewController with tableview 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?

Answer

1) In your cellForRowAtIndexPath: method, assign button tag as index:

cell.yourbutton.tag = indexPath.row;

2) Add target and action for your button as below:

[cell.yourbutton addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

3) Code actions based on index as below in ViewControler:

-(void)yourButtonClicked:(UIButton*)sender
{
     if (sender.tag == 0) 
     {
         // Your code here
     }
}

Updates for multiple Section:

You can check this link to detect button click in table view for multiple row and section.

Comments