سؤال

Before asking this question, I searched a lot on Google and Stackoverflow. Tried also some examples, but I can't make the function work.

Since the hierarchy of the tableview is changed since iOS 7, is it kind of hard to find a solution.

I got a standard tableview with a couple items and one button on the screen.

I need to get the indexPath.row number when selecting an item from the tableview and clicking on the button.

This is my code

- (IBAction)buttonGetNumber:(id)sender {

    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[(UIView *)[button superview] superview]];
    NSLog(@"%i", indexPath.row);
}

This keeps returning a '0', no matter which item I select from the tableview.

I also tried this (2):

- (IBAction)buttonGetNumber:(id)sender {
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *) [[button superview] superview];
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    NSLog(@"%i", index.row);
}

This also returns a '0'.

I also tried this (3):

- (IBAction)buttonGetNumber:(id)sender {
    UIButton *senderButton = (UIButton *)sender;
    UITableViewCell *buttonCell = (UITableViewCell *)[[senderButton superview] superview];
    UITableView* table = (UITableView *)[buttonCell superview];
    NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
    NSInteger rowOfTheCell = [pathOfTheCell row];
    NSLog(@"%i", rowOfTheCell);
}

And this makes the application crash.

Any clue how I can solve this?

enter image description here

هل كانت مفيدة؟

المحلول

Create an instance variable _lastClickedRow Set it with tableview delegate like below. And when you click the to "Get Row" button use _lastClickedRow.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    _lastClickedRow = indexPath.row;
}

- (IBAction)buttonGetNumber:(id)sender {

    NSLog(@"%d" , _lastClickedRow);
}

نصائح أخرى

If for some reason selected cell doesn't work for you (e.g. for a multiple selection case), you could get row from sender's frame:

- (IBAction)buttonGetNumber:(id)sender
{
    CGPoint buttonOrigin = sender.frame.origin;
    CGPoint pointInTableview = [self.tableView convertPoint:buttonOrigin fromView:sender.superview];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTableview];
    if (indexPath) {
        // Do your work
    }
}

You simply set the tag of the UIButton same as the indexPath.row using:

yourButton.tag = indexPath.row;

in didSelectRowForIndexPath:.

Then in buttonGetNumber: method, you get the row number using:

int rowNum = [(UIButton*)sender tag];

Here, you have the advantage of not using any third variable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top