How can I get the indexPath of UIButton in a customized tableViewCell?
iphone
Solution
Define a delegate on the class associated with the Cell's prototype.
// MyCell.h
@protocol MyCellDelegate
- (void)buttonTappedOnCell:(MyCell *)cell;
@end
@interface MyCell : UITableViewCell
@property (nonatomic, weak) id <MyCellDelegate> delegate;
@end
// MyCell.m
@implementation MyCell
- (void)buttonTapped:(id)sender {
[self.delegate buttonTappedOnCell:self];
}
}
@end
Now go to the class you want to make the Cell's delegate. This is probably going to be a UITableView subclass. In the cellForRowAtIndexPath method make sure you assign the delegate of the Cell to self. Then implement the method specified in the protocol.
- (void)buttonTappedOnCell:(MyCell *)cell {
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
int row = indexPath.row;
}
Or if you would prefer a blocks based approach:
// MyCell.h
typdef void(^CellButtonTappedBlock)(MyCell *cell);
@interface MyCell : UITableViewCell
@property (nonatomic, copy) CellButtonTappedBlock buttonTappedBlock;
@end
Then in your tableView's dataSource:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = ....
__weak typeof(self) weakSelf = self;
[cell setButtonTappedBlock:^(MyCell *cell) {
NSIndexPath *indexPath = [weakSelf.tableView indexPathForCell:cell];
// Do stuff with the indexPath
}];
}
Problem
I created a tableViewCell the include an image, two text labels and a uibutton. The button is allocated to an action method (e.g. viewButtonPused:sender). I'm used to handle row selection with tableView:didSelectRowAtIndexPath: so I could tell which row was selected. But with the uibutton and its action method .... How can I tell? Thanks in advance.