Wednesday, January 30, 2013

which index path was the button pressed UITableViewCell http://stackoverflow.com/questions/7466060/custom-uitableviewcell-with-button

http://stackoverflow.com/questions/7466060/custom-uitableviewcell-with-button

 subclassed UITableViewCell and added a button to it. How do I response to the event when the button is touched? I also need to know which index path was the button pressed on.

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {      static NSString *CellIdentifier = @"CustomTableCell";        CustomTableCell *cell = (CustomTableCell *)      [tableView dequeueReusableCellWithIdentifier:CellIdentifier];      if (cell == nil) {          NSArray *topLevelObjects = [[NSBundle mainBundle]                                      loadNibNamed:@"CustomTableCell"                                      owner:nil options:nil];          for (id currentObjects in topLevelObjects){              if ([currentObjects isKindOfClass:[StatusTableCell class]]){                  cell = (StatusTableCell *) currentObjects;                  break;              }          }                                 }      cell.customButton.tag = indexPath.row;      return cell;  }
  

If you have added the UIButton by code in your UITableViewCell Subclass you can use the following code to add an action for it.

  //In UITableViewCell subclass      [customButton addTarget:self                  action:@selector(aMethod:)       forControlEvents:UIControlEventTouchDown];

And then you have already written the code for accessing the row number by setting,

   cell.customButton.tag = indexPath.row;

You can get the tag value in the aMethod and access the indexPath.row value like below,

  //In UITableViewCell subclass      -(IBAction)aMethod:(UIButton*)button      {          NSLog(@"indexPath.row value : %d", button.tag);      }
  
  

You can assign the IBAction in the CustomTableCell Nib and in the function do something like this:

  - (IBAction) btnDoSomethingPressed:(id)sender {      NSIndexPath *indexPath = [yourTableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];       //Use indexPath (or indexPath.row) like you would in a UITableViewDelegate method   }

No comments:

Post a Comment