iPhone - How to determine in which cell a button was pressed in a custom UITableViewCell

后端 未结 10 1928
遥遥无期
遥遥无期 2021-01-01 15:45

I currently have a UITableView that is populated with a custom UITableViewCell that is in a separate nib. In the cell, there are two buttons that are wired to actions in th

10条回答
  •  渐次进展
    2021-01-01 16:18

    There are multiple methods to fix the problem.

    1. You can use the "tag" property Give the value indexPath.row as the tag value for the button.
      btn.tag = indexPath.row;

    Then in the button function, you can easily access the tag value and it will be the index for the clicked button.

    -(void)btnClicked:(id)sender
    {
        int index = [sender tag];
    }
    
    1. You can use the layer property Add the indexPath as the value in the layer dictionary.

      [[btn layer] setValue:indexPath forKey:@"indexPath"];

    This indexPath is accessible from the button action function.

    -(void)btnClicked:(id)sender
    {
        NSIndexPath *indexPath = [[sender layer] valueForKey:@"indexPath"];
        int index = indexPath.row;
    }
    

    With this method you can pass multiple values to the button function just by adding new objects in the dictionary with different keys.

提交回复
热议问题