在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
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
)
}
}
}
其他回答
迅速:
如果你没有tableView头文件:
tableView.setContentOffset(CGPointMake(0, UIApplication.sharedApplication().statusBarFrame.height ), animated: true)
如果有:
tableView.setContentOffset(CGPointMake(0, -tableViewheader.frame.height + UIApplication.sharedApplication().statusBarFrame.height ), animated: true)
不使用
tableView.setContentOffset(.zero, animated: true)
它有时会不正确地设置偏移量。例如,在我的例子中,单元格实际上略高于带有安全区域嵌入的视图。不好的。
而不是使用
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
我使用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
}
}
}
}
Swift 4通过扩展,处理空表视图:
extension UITableView {
func scrollToTop(animated: Bool) {
self.setContentOffset(CGPoint.zero, animated: animated);
}
}
UITableView是UIScrollView的子类,所以你也可以使用:
[mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
Or
[mainTableView setContentOffset:CGPointZero animated:YES];
在Swift中:
mainTableView.setContentOffset(CGPointZero, animated:true)
在Swift 3及以上版本中:
mainTableView.setContentOffset(.zero, animated: true)