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

后端 未结 10 1871
遥遥无期
遥遥无期 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:13

    Much easier solution is to define your button callback with (id)sender and use that to dig out the table row index. Here's some sample code:

    - (IBAction)buttonWasPressed:(id)sender
    {
        NSIndexPath *indexPath =
            [self.myTableView
             indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
        NSUInteger row = indexPath.row;
    
        // Do something with row index
    }
    

    Most likely you used that same row index to create/fill the cell, so it should be trivial to identify what your button should now do. No need to play with tags and try to keep them in order!

    Clarification: if you currently use -(IBAction)buttonWasPressed; just redefine it as -(IBAction)buttonWasPressed:(id)sender; The additional callback argument is there, no need to do anything extra to get it. Also remember to reconnect your button to new callback in Interface Builder!

提交回复
热议问题