在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是section 0,第0行。可能我的表视图将从第5节开始。
所以当我调用:
[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
有其他方法滚动到表视图的顶部吗?
在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是section 0,第0行。可能我的表视图将从第5节开始。
所以当我调用:
[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
有其他方法滚动到表视图的顶部吗?
当前回答
我发现强迫UITableViewController在iPhone、iPad和macCatalyst (macOS)下滚动到顶部的最简单方法如下:
准备返回0从[tableView:numberOfRowsInSection:] 电话(自我。tableView reloadData] 电话(自我。tableView layoutIfNeeded] 准备从[tableView:numberOfRowsInSection:]中返回实际的行数 电话(自我。tableView reloadData]
其他回答
迅速:
tableView.setContentOffset(CGPointZero, animated: true)
如果你不想要滚动,你可以启动和停止滚动动画,只要你启动它。
$('document').ready(function() {
$("html, body").animate({ scrollTop: 0 }, 500);
return true;
});
此外,为了使'x'和'y'的值动画化,传入0,0将立即将页面滚动到左上角。
window.scrollTo(x, y);
Swift 5, iOS 13
我知道这个问题已经有很多答案了,但从我的经验来看,这个方法总是有效的:
let last = IndexPath(row: someArray.count - 1, section: 0)
tableView.scrollToRow(at: last, at: .bottom, animated: true)
如果你正在处理动画(比如键盘)或某些异步任务,这尤其正确——其他答案通常会滚动到底部。如果由于某种原因,这不能让你一直到底部,这几乎肯定是因为竞争动画,所以解决方法是将这个动画分派到主队列的末尾:
DispatchQueue.main.async {
let last = IndexPath(row: self.someArray.count - 1, section: 0)
self.tableView.scrollToRow(at: last, at: .bottom, animated: true)
}
这似乎是多余的,因为你已经在主队列上了,但这并不是因为它序列化了动画。
scrollToRow解决方案,它修复了空TableView(需要搜索)的问题。
import UIKit
extension UITableView {
public func scrollToTop(animated: Bool = false) {
if numberOfRows(inSection: 0) > 0 {
scrollToRow(
at: .init(row: 0, section: 0),
at: .top,
animated: animated
)
}
}
}
在Swift-3中:
self.tableView.setContentOffset(CGPoint.zero, animated: true)