在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
因为我的tableView充满了各种各样的insets,这是唯一一件工作得很好的事情:
斯威夫特3
if tableView.numberOfSections > 0 && tableView.numberOfRows(inSection: 0) > 0 {
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
}
斯威夫特2
if tableView.numberOfSections > 0 && tableView.numberOfRowsInSection(0) > 0 {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true)
}
其他回答
这是代码ScrollTableView到顶部编程
迅速:
self.TableView.setContentOffset(CGPointMake(0, 1), animated:true)
注意:此答案不适用于iOS 11及更高版本。
我更喜欢
[mainTableView setContentOffset:CGPointZero animated:YES];
如果你在你的表格视图中有一个top inset,你必须减去它:
[mainTableView setContentOffset:CGPointMake(0.0f, -mainTableView.contentInset.top) animated:YES];
在Swift-3中:
self.tableView.setContentOffset(CGPoint.zero, animated: true)
在Swift 5中,非常感谢@Adrian的回答
extension UITableView{
func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section)
}
func scrollToTop(_ animated: Bool = false) {
let indexPath = IndexPath(row: 0, section: 0)
if hasRowAtIndexPath(indexPath: indexPath) {
scrollToRow(at: indexPath, at: .top, animated: animated)
}
}
}
用法:
tableView.scrollToTop()
如果你不想要滚动,你可以启动和停止滚动动画,只要你启动它。
$('document').ready(function() {
$("html, body").animate({ scrollTop: 0 }, 500);
return true;
});
此外,为了使'x'和'y'的值动画化,传入0,0将立即将页面滚动到左上角。
window.scrollTo(x, y);