UITableView Cell - get IndexPath.row from a button?

I currently have a button defined in a cell, and a way to track its UITouchDown action, as shown:

- (void) clickedCallSign:(id)sender { int index = [sender tag]; NSLog(@"event triggered %@",index); } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { //Callsign button UIButton *button; CGRect rect = CGRectMake(TEXT_OFFSET_X, BORDER_WIDTH, LABEL_WIDTH, LABEL_HEIGHT); button = [[UIButton alloc] initWithFrame:rect]; cell.tag=[indexPath row]; button.tag=[indexPath row]; [button addTarget:self action:@selector(clickedCallSign:) forControlEvents:UIControlEventTouchDown]; [button setBackgroundColor:[UIColor redColor]]; [button setTitle:@"hello" forState:UIControlStateNormal]; [cell.contentView addSubview:button]; [button release]; } 

However, when I click on a cell in the simulator, the console debug message is β€œevent triggered (null)”, and soon my application will work.

How can I get indexPath.row correctly in my clickedCallSign method?

+6
objective-c iphone uitableview uibutton selector
source share
3 answers

Firstly, index is int , so your NSLog should look like this (note %d ):

 NSLog(@"event triggered %d", index); 

(Perhaps this leads to a failure, but it is also likely that something else is happening at all, which causes instability.)

+2
source share

A tag is good until you have two sections and rows. Try another way to get the index path:

 - (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath { //... [button addTarget:self action:@selector(clickedCallSign:withEvent:) forControlEvents:UIControlEventTouchDown]; //... } // Get the index path of the cell, where the button was pressed - (NSIndexPath*)indexPathForEvent:(id)event { NSSet *touches = [event allTouches]; UITouch *touch = [touches anyObject]; CGPoint currentTouchPosition = [touch locationInView:self.tableView]; return [self.tableView indexPathForRowAtPoint:currentTouchPosition]; } - (IBAction)clickedCallSign:(id)sender withEvent:(UIEvent*)event { NSIndexPath* buttonIndexPath = [self indexPathForEvent:event]; } 
+2
source share

If you do not want to use the tag field, click the button to call this method:

 - (void)tapAccessoryButton:(UIButton *)sender { UIView *parentView = sender.superview; // the loop should take care of any changes in the view heirarchy, whether from // changes we make or apple makes. while (![parentView.class isSubclassOfClass:UITableViewCell.class]) parentView = parentView.superview; if ([parentView.class isSubclassOfClass:UITableViewCell.class]) { UITableViewCell *cell = (UITableViewCell *) parentView; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath]; } } 
+2
source share

All Articles