I have a button (action) connected to my UITableViewCell class. How do I get indexPath of tableView from tableViewCell class?
@implement myTableViewCell
-(IBAction)buttonPressed{
// Do something to get indexPath?
}
I have a button (action) connected to my UITableViewCell class. How do I get indexPath of tableView from tableViewCell class?
@implement myTableViewCell
-(IBAction)buttonPressed{
// Do something to get indexPath?
}
in CustomCell.h
@property (nonatomic, strong) UIButton *btn;
in tableView dataSource file
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell.btn addTarget:self action:@selector(buttonPressed:event:) forControlEvents:UIControlEventTouchUpInside];
}
//button action
-(void)buttonPressed:(UIControl *)sender event:(id)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPos = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPos];
if(indexPath != nil){
//to do with indexPath
}
}
//button action in cell class
- (void)buttonPressed:(UIButton *)btn event:(id)event{
UIView *superView = [btn superview];
while (superView && ![superView isKindOfClass:[UITableView class]]) {
superView = [superView superview];
}
if ([superView isKindOfClass:[UITableView class]]) {
UITableView *tableView = (UITableView *)superView;
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPos = [touch locationInView:tableView];
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPos];
if(indexPath != nil){
NSLog(@"tableView.row:%d", indexPath.row);
}
}
}
Like in this answer:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
Add action to your button with sender:
[btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
then:
- (void) buttonPressed:(id)sender{
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:tableView];
NSIndexPath *hitIndex = [tableView indexPathForRowAtPoint:hitPoint];
}
get the table from the cell. place this inside the cell
- (UITableView*)tableView {
if (tableView == nil) {
tableView = (UITableView*)self.superview;
while (tableView && ![tableView isKindOfClass:[UITableView class]]) {
tableView = (UITableView*)tableView.superview;
}
}
return tableView;
}
inside your IBAction ask for the indexpath
NSIndexPath *p = [self.tableView indexPathForCell:self];
TADA ;)