在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
在斯威夫特
your row = selectioncellRowNumber 你的section如果你有= selectionNumber如果你没有set为零
/ / UITableViewScrollPosition。中间或底部或顶部
var lastIndex = NSIndexPath(forRow: selectioncellRowNumber, inSection: selectionNumber)
self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
其他回答
在Swift-3中:
self.tableView.setContentOffset(CGPoint.zero, animated: true)
我遇到了一个问题,在一个空的tableView上尝试一些方法。下面是Swift 4处理空表视图的另一个选项。
extension UITableView {
func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRows(inSection: indexPath.section)
}
func scrollToTop(animated: Bool) {
let indexPath = IndexPath(row: 0, section: 0)
if self.hasRowAtIndexPath(indexPath: indexPath) {
self.scrollToRow(at: indexPath, at: .top, animated: animated)
}
}
}
用法:
// from yourViewController or yourTableViewController
tableView.scrollToTop(animated: true)//or false
我使用tabBarController,我有几个节在我的表视图在每个选项卡,所以这是我最好的解决方案。
extension UITableView {
func scrollToTop(){
for index in 0...numberOfSections - 1 {
if numberOfSections > 0 && numberOfRows(inSection: index) > 0 {
scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true)
break
}
if index == numberOfSections - 1 {
setContentOffset(.zero, animated: true)
break
}
}
}
}
斯威夫特3
tableView.setContentOffset(CGPoint.zero, animated: true)
如果视图。setcontenttoffset不起作用。
使用:
tableView.beginUpdates()
tableView.setContentOffset(CGPoint.zero, animated: true)
tableView.endUpdates()
如果你不想要滚动,你可以启动和停止滚动动画,只要你启动它。
$('document').ready(function() {
$("html, body").animate({ scrollTop: 0 }, 500);
return true;
});
此外,为了使'x'和'y'的值动画化,传入0,0将立即将页面滚动到左上角。
window.scrollTo(x, y);