ios - UITableView ScrollToRowAtIndexPath 方法不起作用

标签 ios uitableview scroll

我有一个 UITableView 作为 View 的 subview 。在填充表时的 ViewController 中,我突出显示其中一行并保留该行的 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 方法中,我希望表格滚动到突出显示的单元格。

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

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

最佳答案

如果该行不在屏幕上,它还不会被 TableView 加载。这意味着该单元格的 cellForRowAtIndexPath 将不会被调用。您将希望以不依赖于 View 加载的方式选择此索引。在调用 scrollToRowAtIndexPath 之前尝试此操作:

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

关于ios - UITableView ScrollToRowAtIndexPath 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28727072/

相关文章:

ios - 从自定义 UIViewController 和 CocoaPods 库多重继承

ios - UITableViewCell 中的 UISwitch 和 UIButton,如何识别它们

ios - 如何通过单击表格单元格中的按钮从表格单元格获取标签值?

ios - 选择时 uitableviewcell 损坏(从底部看到)

jquery - 如何根据滚动创建图像平移效果?

cocoa - 为 NSTableView 启用滚动

java - java 客户端 v4.0 中 scrollTo 和 scrollToExact 的替换

ios - ios中如何获取所有绘制的点?

ios - 滑动和旋转 UIView

ios - 如何调整 UITableViewController 中的部分和行?