我有一个 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/