I created a TableView having a custom UITableViewCell. A button is associated with each row of tableview. Now I want to know the row number on click of a button, so that I would know that of which row button has been clicked. I have given a try to few things found on stack but nothing is working.
I have tried this code -:
-(void)button1Tapped:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);
}
But this is also not working.
Thanks for helping me out.
add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.
A list of indexes that together represent the path to a specific location in a tree of nested arrays.
indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.
try with this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[[cell contentView] setBackgroundColor:[UIColor clearColor]];
[[cell backgroundView] setBackgroundColor:[UIColor clearColor]];
[cell.Mybutton addTarget:self action:@selector(btnCommentClick:) forControlEvents:UIControlEventTouchUpInside];
}
cell.Mybutton.tag=indexPath.row;
}
-(void)btnCommentClick:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
NSLog(@"current Row=%d",senderButton.tag);
NSIndexPath *path = [NSIndexPath indexPathForRow:senderButton.tag inSection:0];
}
The best way to know which row of tableView is clicked is by setting tag value of cell button in cellForRowAtIndexPath method while using custom cell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With