Search code examples
iphoneuitableviewuibuttonnsindexpath

how to determine the row with button pressed?


I have my custom uitableviewcell. It has the uibutton, uibutton with action. So how do I know indexPath of the row with pressed uibutton??

Target: uibuttons on each rows has an image. So when user taps the button it shows the alertview and if answer is "yes" uibutton's image changes.


Solution

  • Try below code snippet:

    In cellForRowAtIndexPath method. set indexpath.row as button tag

    [cellButton addTarget:self action:@selector(cellBottonClicked:) forControlEvents:UIControlEventTouchUpInside];
    cellButton.tag = indexPath.row;

    -(IBAction) cellBottonClicked:(id)sender{
        NSInteger row = [sender tag];
        //you can get indexpath from row
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0]; 
        CustomTableViewCell *cell = (CustomTableViewCell *)[self.tableView  cellForRowAtIndexPath:indexPath];
        // from this cell you can fetch and change image of selected cell's button. 
    }
    

    [EDIT : Change Only image of Button]

    If you only required to change Image of Button on click event.then I think, you do not need for indexpath or cell.

    try this code. Hope it will helps:

    -(IBAction) cellBottonClicked:(id)sender{
       UIButton *btn = (UIButton *)sender;
       [btn setImage:yourImage forState:UIControlStateNormal];
     }