Linda Keating
Linda Keating

Reputation: 2435

UITableView ScrollToRowAtIndexPath method not working

I have a UITableView as a subview of a View. In the ViewController when the table is being populated I'm highlighting one of the rows and keeping a record of the indexPath for that row. I'm doing this in the cellforRowAtIndexPath method.

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
favouriteCellView *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseID"];

QBCOCustomObject *favouriteObject = [_favouriteResults objectAtIndex:indexPath.row];

if (favouriteObject.userID == self.user.ID) {
    UIView *bgColor = [[UIView alloc] init];
    bgColor.backgroundColor = [UIColor colorWithRed:173.0f/255.0f green:146.0f/255.0f blue:237.0f/255.0f alpha:.5];
    self.highlightedRowIndex = indexPath;
    [cell setSelectedBackgroundView:bgColor];
    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}
return cell;

}

Then in the viewDidAppear Method I want the table to scroll to the highlighted cell.

-(void)viewDidAppear:(BOOL)animated{
     [self.tableView scrollToRowAtIndexPath:self.highlightedRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];      
}

However I've double checked that the method is being hit with a breakpoint, but unfortunately the highlighted row is not being scrolled to the top of the table as I'd expected. AM I misunderstanding the scrollToRowAtIndexPath method? Or have I left something out of the above code.

Upvotes: 0

Views: 906

Answers (1)

Ian MacDonald
Ian MacDonald

Reputation: 14000

If the row is not on screen, it will not yet be loaded by the table view. This means your cellForRowAtIndexPath for that cell will not yet be called. You'll want to choose this index in a way that does not depend on the view loading. Try this before you call scrollToRowAtIndexPath:

NSInteger row = 0;
for (QBCOCustomObject *object in _favouriteResults) {
  if (object.userID == self.user.ID) break;
  row++;
}
self.highlightedRowIndex = [NSIndexPath indexPathForRow:row inSection:0];

Upvotes: 1

Related Questions