在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
斯威夫特3
tableView.setContentOffset(CGPoint.zero, animated: true)
如果视图。setcontenttoffset不起作用。
使用:
tableView.beginUpdates()
tableView.setContentOffset(CGPoint.zero, animated: true)
tableView.endUpdates()
其他回答
添加到已经说过的,你可以创建一个扩展(Swift)或类别(Objective C),使这在未来更容易:
迅速:
extension UITableView {
func scrollToTop(animated: Bool) {
setContentOffset(CGPointZero, animated: animated)
}
}
任何时候你想要滚动任何给定的tableView到顶部,你可以调用以下代码:
tableView.scrollToTop(animated: true)
func scrollToTop() {
NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
[tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
调用这个函数,无论你想让UITableView滚动到顶部
最好不要使用NSIndexPath(空表),也不要假设顶点是CGPointZero(内容嵌入),这就是我使用的-
[tableView setContentOffset:CGPointMake(0.0f, -tableView.contentInset.top) animated:YES];
希望这能有所帮助。
要在完成时有一个完成,请添加此扩展
// MARK: - UIScrollView
extension UIScrollView {
/// Animate scroll to top with completion
///
/// - Parameters:
/// - duration: TimeInterval
/// - completion: Completion block
func animateScrollToTop(withDuration duration: TimeInterval,
completion: @escaping (()->())) {
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.setContentOffset(CGPoint.zero, animated: false)
}, completion: { finish in
guard finish else {
return
}
completion()
})
}
}
tableView.animateScrollToTop(withDuration: 0.25) {
// Finish
}
迅速:
self.scripSearchView.quickListTbl?.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)