滚动到Table View Header顶部

时间:2016-10-23 15:04:28

标签: ios swift uitableview

我有一个UITableView标题,占据了整个屏幕框架。

每次应用进入后台,然后回到前台/活动状态时,我希望将屏幕设置回标题顶部

我之前只看到过使用类似self.tableView.scrollToRow(at: top, at: .top, animated: true)之类的answers滚动到表格顶部的答案,但是这样做并不起作用,因为它只会滚动回UITableView的第0行第0行而不是UITableView标题的顶部。

有什么想法吗?

谢谢!

修改:试过这个

override func viewWillAppear(_ animated: Bool) {
    self.tableView.setContentOffset( CGPoint(x: 0, y: 0) , animated: true)
}

以下是一些值得注意的表格设置代码:

// Set up Frames
let headerFrame: CGRect = UIScreen.main.bounds
// Background Table
self.tableView.isPagingEnabled = true

// Set up Table Header
let header = UIView(frame: headerFrame)
self.tableView.tableHeaderView = header    

2 个答案:

答案 0 :(得分:9)

TableView是一个滚动视图子类,所以我想这应该可行:

 self.tableView.setContentOffset( CGPoint(x: 0, y: 0) , animated: true)

当应用进入前景时,不会调用ViewWillAppear。注册VC为UIApplicationWillEnterForegroundNotification

答案 1 :(得分:0)

您可以滚动到节标题,尝试以下代码:

DispatchQueue.main.async {
    let indexPath = IndexPath(row: NSNotFound, section: yourSectionIndex)
    self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}

对于行添加:NSNotFound

根据您的要求更改“scrollToRow”中的 .top/.bottom。