在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
以下是我在iOS 11上正确运行的方法:
extension UIScrollView {
func scrollToTop(animated: Bool) {
var offset = contentOffset
if #available(iOS 11, *) {
offset.y = -adjustedContentInset.top
} else {
offset.y = -contentInset.top
}
setContentOffset(offset, animated: animated)
}
}
其他回答
在斯威夫特
your row = selectioncellRowNumber 你的section如果你有= selectionNumber如果你没有set为零
/ / UITableViewScrollPosition。中间或底部或顶部
var lastIndex = NSIndexPath(forRow: selectioncellRowNumber, inSection: selectionNumber)
self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
最好不要使用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
}
我必须把状态栏和导航栏的和乘以-1 *,因为它离屏幕有那么高,
self.tableView.setContentOffset(CGPointMake(0 , -1 *
(self.navigationController!.navigationBar.height +
UIApplication.sharedApplication().statusBarFrame.height) ), animated:true)
注意:此答案不适用于iOS 11及更高版本。
我更喜欢
[mainTableView setContentOffset:CGPointZero animated:YES];
如果你在你的表格视图中有一个top inset,你必须减去它:
[mainTableView setContentOffset:CGPointMake(0.0f, -mainTableView.contentInset.top) animated:YES];