I've got dynamic tableView and one problem. In each tableCell are two buttons. I'm trying to get indexPath.row on button touched but with no success.
My code:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.homeTableView indexPathForSelectedRow];
NSLog(@"%d", indexPath.row);
}
How can I get indexPath.row for touced button (Segue connections are over this two buttons->two connections)?
It's not working because you do not select row when you click button.
With two buttons I would disconnect your segues from buttons and do 2 manual segues in IB then add code like that to handle them:
-(void)button1Pressed:(id)sender {
UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *clickedButtonIndexPath = [self.homeTableView indexPathForCell:clickedCell];
...
[self performSegueWithIdentifier:@"YourManualSegueIdentifier1" sender:self];
}
Edit for second option:
In your MyTableViewCell.h:
@interface MyTableViewCell : UITableViewCell
...
@property (strong, nonatomic) NSIndexPath *cellIndexPath;
...
@end
In your MyTableViewCell.m:
-(void)button1Pressed:(id)sender {
...
NSInteger row = cellIndexPath.row;
...
}
In your MyTableViewController.m:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// remember index here!
[cell setCellIndexPath:indexPath];
....
return cell;
}
Apple change the UITableViewCell hierarchy in iOS 7
Using iOS 6.1 SDK
<UITableViewCell>
| <UITableViewCellContentView>
| | <UILabel>
Using iOS 7 SDK
<UITableViewCell>
| <UITableViewCellScrollView>
| | <UITableViewCellContentView>
| | | <UILabel>
So if you want to get indexpath at button index then use following code Using iOS 6 or later SDK
UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *clickedButtonPath = [book_table indexPathForCell:clickedCell];
NSLog(@"index=%@",clickedButtonPath);
Using iOS 7 or 7+ SDK
UITableViewCell *clickedCell = (UITableViewCell *)[[[sender superview] superview]superview];
NSIndexPath *clickedButtonPath = [book_table indexPathForCell:clickedCell];
NSLog(@"index=%ld",(long)clickedButtonPath.item);
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