Define a delegate in the class associated with the Cell 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 delegate. This will probably be a subclass of UITableView. In the cellForRowAtIndexPath method, make sure you assign a Cell delegate to yourself. Then we implement the method specified in the protocol.
- (void)buttonTappedOnCell:(MyCell *)cell { NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; int row = indexPath.row; }
Or, if you prefer a block-based approach:
//MyCell.h
typdef void(^CellButtonTappedBlock)(MyCell *cell); @interface MyCell : UITableViewCell @property (nonatomic, copy) CellButtonTappedBlock buttonTappedBlock; @end
Then in your tableView 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];
source share