Jeeter
Jeeter

Reputation: 6085

UITableView - Select a row programmatically

So I thought with all the questions here on StackOverflow on this topic, I wouldn't need to ask this question. Well, none of the answers worked for me.

Basically, I am trying to call -didSelectRowAtIndexPath: manually when the user presses a button:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self tableView:[viewControllers objectAtIndex:1] didSelectRowAtIndexPath:indexPath];

where viewControllers is an array of UITableViews, fully initialized and everything. But when I run the code, I get it erroring here:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    currentUnit = [tableView cellForRowAtIndexPath:indexPath]; //on this line
    [self prepareSecondPageController: [currentUnit.textLabel text]];
    [unit2 setText:[NSString stringWithFormat:@"Unit Two: %@", currentCompatCategory]];
}

and the console reads:

-[UITableViewController cellForRowAtIndexPath:]: unrecognized selector sent to instance 0xc177640

(0xc177640 is the tableView)

I don't know if this will help, but this is what my indexPath looks like in the debugger:

enter image description here

Upvotes: 0

Views: 691

Answers (3)

Dipu Rajak
Dipu Rajak

Reputation: 693

you are passing Controller instead of tableView. Probably, that's why app is crashing.

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    // Assuming viewControllers is the collection of UITableViewControllers.
    UITableView *tableView = (UITableView *)[viewControllers objectAtIndex:1].tableView;
    [self tableView:tableView didSelectRowAtIndexPath:indexPath];

Upvotes: 1

Sergey  Pekar
Sergey Pekar

Reputation: 8745

You are passing wrong parameter to didSelectRowAtIndexPath method. The first parameter must be your view controller's table view not array of TableViewControllers (According to your exception information it seems your array is not array of table views ).

[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

Upvotes: 1

blazejmar
blazejmar

Reputation: 1090

It looks that in array there are TableViewControllers not TableViews. This is causing the error as TVC doesn't have method cellForRowAtIndexPath:.

Upvotes: 0

Related Questions