UITableView ScrollToRowAtIndexPath 方法不起作用

UITableView ScrollToRowAtIndexPath method not working

我有一个 UITableView 作为视图的子视图。在 ViewController 中,当 table 被填充时,我突出显示其中一行并记录该行的 indexPath。我在 cellforRowAtIndexPath 方法中执行此操作。

-(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;

}

然后在 viewDidAppear 方法中,我希望 table 滚动到突出显示的单元格。

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

不过,我已经仔细检查过该方法是否遇到了断点,但不幸的是,突出显示的行没有像我预期的那样滚动到 table 的顶部。我误解了 scrollToRowAtIndexPath 方法吗?还是我在上面的代码中遗漏了一些东西。

如果该行不在屏幕上,则 table 视图还不会加载它。这意味着该单元格的 cellForRowAtIndexPath 尚未被调用。您将希望以不依赖于视图加载的方式选择此索引。在调用 scrollToRowAtIndexPath:

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