1

There is UITableViewCell which contain UIButton.

In my cellForRowAtIndexPath:

cell.toCartBtn.tag = indexPath.row;
[cell.toCartBtn addTarget:self
           action:@selector(toCart:) forControlEvents:UIControlEventTouchDown];

In toCart method I need to get row and section by tapped button tag. How can I do it?

Romowski
  • 1,518
  • 5
  • 25
  • 50

5 Answers5

10

See this code

- (void)toCart:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath)
    {
     ...
    }
}
brainray
  • 12,512
  • 11
  • 67
  • 116
Oh Seung Kwon
  • 431
  • 3
  • 11
2

Use this simple code if UIButton is subview in cell

- (void)toCart:(id)sender 
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *cell=(UITableViewCell*)senderButton.superView;
NSIndexPath *index = [tableView indexPathForCell:cell];
}
NANNAV
  • 4,875
  • 4
  • 32
  • 50
0

Create a custom UITableViewCell subclass and handle the touch in there.

Then define a delegate for your custom table view cell and when you create the cell, assign your table view data source as the delegate.

When the cell handles the touch, send a message to the delegate and then find the index path from the table view.

-(void)customTableViewCellButtonPressed:(CustomTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ...
}
kball
  • 4,923
  • 3
  • 29
  • 31
0

try this:

- (void)toCart:(id)sender {
    CGPoint button1 = [sender convertPoint:CGPointZero toView:self.tblName];
    NSIndexPath *index = [self.tableView indexPathForRowAtPoint:button1];

    //use index variable
}

and also see for more details for your bug...

Detecting which UIButton was pressed in a UITableView

Community
  • 1
  • 1
DharaParekh
  • 1,730
  • 1
  • 10
  • 17
0

For Swift

    let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to: self.tableViewItems)
    let indexPath = self.tableViewItems.indexPathForRow(at: buttonPosition)
    if (indexPath != nil)
    {
        print(indexPath?.section)
        print(indexPath?.row)
    }
Waseem Sarwar
  • 2,645
  • 1
  • 21
  • 18