Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 the custom cell class. When I click one of the buttons, I can call the proper method, but I need to know which row the button was pressed in. The tag property for each button is coming as 0. I don't need to know when the entire cell is selected, just when a particular button is pressed, so I need to know which row it is so I can update the proper object.

like image 707
Tai Squared Avatar asked Jun 22 '09 22:06

Tai Squared


People also ask

How do you get the indexPath row when a button in a cell is tapped?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

How do I know which button is clicked in Swift?

cause first is you have to click from the 3 button after clicking from the 3 button then you will click idenfifywhichpressed button and this button will identify or print which button from the 3 was pressed. During setup, mark the button tag as 1,2,3... When your click action done, check the sender.

What is prototype cell?

A prototype cell acts a template for your cell's appearance. It includes the views you want to display and their arrangement within the content area of the cell. At runtime, the table's data source object creates actual cells from the prototypes and configures them with your app's data.


1 Answers

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!

like image 190
JOM Avatar answered Jan 03 '23 20:01

JOM