scrollViewDidScroll以奇怪的内容调用OffsetY



我有一个UIViewController,它有一个NSFetchedResultsController。在将行插入到顶部后,我想使行保持可见,因为它们在插入之前的位置。这意味着我需要进行一些计算以在更新后立即保持 contentOffSetY。计算是正确的,但我注意到scrollViewDidScroll在滚动到我指定的 contentOffsetY 后被调用,这会导致损坏状态。这是日志记录:

Will apply an corrected Y value of: 207.27359771728516
Scrolled to: 207.5
Corrected to: 207.27359771728516
Scrolled to: 79.5 <-- Why is this logline here?

您可以直接克隆一个示例项目:https://github.com/Jasperav/FetchResultControllerGlitch(提交 https://github.com/Jasperav/FetchResultControllerGlitch/commit/d46054040139afeeb648e1e0b5b113bd98685b4a,最新版本的项目只有故障,对scrollViewDidScroll方法的奇怪调用现在已经消失了。如果您修复故障,我将奖励赏金。只需克隆最新版本,运行它并滚动一点。你会看到奇怪的内容偏移(故障))。运行该项目,您将看到奇怪的输出。这是controllerDidChangeContent方法:

public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
let currentSize = tableView.contentSize.height
UIView.performWithoutAnimation {
tableView.endUpdates()
let newSize = tableView.contentSize.height
let correctedY = tableView.contentOffset.y + newSize - currentSize
print("Will apply an corrected Y value of: (correctedY)")
tableView.setContentOffset(CGPoint(x: 0,
y: correctedY),
animated: false)
print("Corrected to: (correctedY)")
}
}

如果我在tableView.endUpdates()后立即呼叫tableView.layoutIfNeeded,则已经调用了委托。调用委托方法会导致什么?有什么办法不滚动吗?

我下载了您的代码并进行了一些调整以解决故障问题。这是我所做的。

  1. 将表视图estimatedRowHeight属性设置为某个数字
init() {
super.init(frame: .zero, style: .plain)
estimatedRowHeight = 50.0
register(MyTableViewCell.self, forCellReuseIdentifier: "cell")
}
  1. 创建了一个函数来处理 UITableView 重新加载操作,而无需修改当前 contentOffset
func reloadDataWithoutScroll() {
let lastScrollOffset = contentOffset
beginUpdates()
reloadData()
layoutIfNeeded()
endUpdates()
layer.removeAllAnimations()
setContentOffset(lastScrollOffset, animated: false)
}
  1. 更新了controllerDidChangeContent函数以使用reloadDataWithoutScroll函数
UIView.performWithoutAnimation {
tableView.performBatchUpdates({
tableView.insertRows(at: inserts, with: .automatic)
})   
inserts.removeAll()
tableView.reloadDataWithoutScroll()
}

当我执行这些更改时,添加新行时它不会滚动。但是,当当前内容偏移量为 0 时,它确实会滚动以显示新添加的行。从逻辑上讲,我认为这不是一个问题。

最新更新