在我正在处理的应用程序中,我有一个简单的样式UITableView,它可以包含一个包含零行的部分。我希望能够使用scrollToRowAtIndexPath滚动到此部分:atScrollPosition:animated:但是当我尝试滚动到此部分时由于缺少子行而出现错误。

Apple的日历应用程序可以执行此操作,如果您在列表视图中查看日历,并且今天日历中没有事件,则今天会插入空白部分,您可以使用“今日”按钮滚动到该部分在屏幕底部的工具栏中。据我所知,Apple可能正在使用自定义的UITableView,或者他们正在使用私有API ......

我能想到的唯一解决方法是在0像素高的位置插入一个空的UITableCell并滚动到那个。但我的理解是,拥有不同高度的单元格对于滚动性能来说真的很糟糕。无论如何我仍然会尝试,也许性能打击不会太差。

<强>更新

由于似乎没有解决方案,我已经向苹果公司提交了一份错误报告。如果这对您也有影响,请提交rdar:// problem / 6263339的副本( Open Radar link)如果你想让它更快地修复它。

更新#2

我对此问题有一个不错的解决方法,请看下面的答案。

有帮助吗?

解决方案

更新:看起来这个错误已在iOS 3.0中修复。您可以使用以下 NSIndexPath 滚动到包含0行的部分:

[NSIndexPath indexPathForRow:NSNotFound inSection:section]

对于仍然使用2.x SDK维护项目的人,我会在此处留下我原来的解决方法。


找到一个不错的解决方法:

CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];
[tableView scrollRectToVisible:sectionRect animated:YES];

上面的代码将滚动tableview,以便可见所需的部分,但不一定在可见区域的顶部或底部。如果你想滚动所以部分位于顶部,请执行以下操作:

CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];
sectionRect.size.height = tableView.frame.size.height;
[tableView scrollRectToVisible:sectionRect animated:YES];

根据需要修改sectionRect,将所需部分滚动到可见区域的底部或中间。

其他提示

这是一个老问题,但Apple仍然没有添加任何有助于或修复该部分没有行的崩溃错误的内容。

对我来说,我真的需要在添加时将新部分滚动到中间,所以我现在使用此代码:

if (rowCount > 0) {
    [self.tableView scrollToRowAtIndexPath: [NSIndexPath indexPathForRow: 0 inSection: sectionIndexForNewFolder] 
                          atScrollPosition: UITableViewScrollPositionMiddle
                                  animated: TRUE];
} else { 
    CGRect sectionRect = [self.tableView rectForSection: sectionIndexForNewFolder];
    // Try to get a full-height rect which is centred on the sectionRect
    // This produces a very similar effect to UITableViewScrollPositionMiddle.
    CGFloat extraHeightToAdd = sectionRect.size.height - self.tableView.frame.size.height;
    sectionRect.origin.y -= extraHeightToAdd * 0.5f;
    sectionRect.size.height += extraHeightToAdd;
    [self.tableView scrollRectToVisible:sectionRect animated:YES];
}

希望你喜欢它 - 它基于Mike Akers的代码,你可以看到,但计算滚动到中间而不是顶部。谢谢迈克 - 你是明星。

采用Swift方法:

if rows > 0 {
    let indexPath = IndexPath(row: 0, section: section)
    self.tableView.setContentOffset(CGPoint.zero, animated: true)
    self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}

else {
    let sectionRect : CGRect = tableView.rect(forSection: section)
    tableView.scrollRectToVisible(sectionRect, animated: true)
}

如果您的部分没有行,请使用此

let indexPath = IndexPath(row: NSNotFound, section: section)
tableView.scrollToRow(at: indexPath, at: .middle, animated: true)

我认为空行可能是去那里的唯一方法。是否有可能重新设计UI以使“空”和“空”。行可以显示有用的东西吗?

我说尝试一下,看看表现如何。他们给出了关于在列表项中使用透明子视图的非常可怕的警告,我没有发现它在我的应用程序中的重要性。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top