MobileKaizen MobileKaizen - 6 months ago 21
Objective-C Question

How to pass NSIndexPath object with addTarget method?

I want to pass NSIndexPath to @selector.
So I used following code, but there is no argument like withObject.
How can I do it?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{

// User taps expanded row
if (selectedIndex == indexPath.row){
selectedIndex = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
}

// User taps different row
if (selectedIndex != -1){
NSIndexPath *prevPath = [NSIndexPath indexPathForRow:selectedIndex inSection:1];
selectedIndex = (int)indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:prevPath, nil] withRowAnimation:UITableViewRowAnimationFade];
}

// User taps new row with unexpanded
selectedIndex = (int)indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];

[favoriteButton addTarget:self action:@selector(favoritePressed:) withObject:indexPath forControlEvents:UIControlEventTouchDown];
[normalButton addTarget:self action:@selector(normalPressed) forControlEvents:UIControlEventTouchDown];
[halfButton addTarget:self action:@selector(halfPressed) forControlEvents:UIControlEventTouchDown];

}

-(void)favoritePressed:(NSIndexPath *)path{
}

Answer

Try like this:

-(void)favoritePressed:(UIButton *)sender{
    //CustomCell : your custom UITableViewCell class name
    CustomCell *cell = (CustomCell) [[sender superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
}

NOTE:

If you set button in content view of CustomCell this will work for you otherwise you need to add other superview for getting the cell.