Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get section number and row number on custom cells button click?

i have tableview with custom cell.the table is divided in many section and rows.i have a custom button on cell. now i want to get section number and row number when i click on that button.? any idea regarding this

like image 840
Rahul Vyas Avatar asked May 30 '09 15:05

Rahul Vyas


2 Answers

You'll need to implement a UIControl event-handling method on your view controller, and set that as the handler for all your buttons. i.e. inside your -tableView:cellForRowAtIndexPath: function you would do something like:

[theCell.button addTarget: self
                   action: @selector(buttonPressed:withEvent:)
         forControlEvents: UIControlEventTouchUpInside];

Then your event handler would look like this:

- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
    UITouch * touch = [[event touches] anyObject];
    CGPoint location = [touch locationInView: self.tableView];
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];

    /* indexPath contains the index of the row containing the button */
    /* do whatever it is you need to do with the row data now */
}
like image 73
Jim Dovey Avatar answered Nov 03 '22 19:11

Jim Dovey


A few thoughts:

You can iterate through the button's superview hierarchy until you find a UITableViewCell, then call - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell on the UITableView.

- (void)buttonClicked:(id)sender {
  UIView *button = sender;

  for (UIView *parent = [button superview]; parent != nil; parent = [parent superview]) {
    if ([parent isKindOfClass: [UITableViewCell class]]) {
      UITableViewCell *cell = (UITableViewCell *) parent;           
      NSIndexPath *path = [self.tableView indexPathForCell: cell];

      // now use the index path

      break; // for
    }
  }
}

You can alternately use the tag of the button to store an index referencing the row. This only holds a single integer, so it makes the most sense when you have a single section, or when you are managing your rows as a flat list.

You can alternately subclass UITableViewCell to encapsulate the button. Your UITableViewCell could respond to the button events and rebroadcast an event to its own delegate, passing self. The event delegate can then call - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell on the UITableView to get the index path.

like image 8
dmercredi Avatar answered Nov 03 '22 18:11

dmercredi