我有一个 TableView ,它从后端获取远程数据,一切正常,我想要完成的是当用户单击任何单元格以导航到其他 ViewController(详细信息 Controller )并按下后退按钮时 TableView 应该滚动到选定的单元格而不是返回顶部 我试过 tableView.scrollToRow
如下所示,但它不起作用?我知道我在我的加载数据函数中调用 tableView.reloadData()
否则它不会加载
class feeds: UITableViewController {
var data = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
LoadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// configur tabl cell
return cell
}
func LoadData(){
// Fetch Feeds to dataArray
// Reload UITable View
self.tableView.reloadData()
let celloffset = UserDefaults.standard.integer(forKey: "celloffset")
if celloffset != 0{
let index = IndexPath(item: celloffset, section: 0)
self.tableView.scrollToRow(at: index, at: UITableViewScrollPosition.middle, animated: false)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UserDefaults.standard.set(indexPath.row, forKey: "celloffset")
// Navigate to Details VC
}
}
任何帮助或想法将不胜感激
最佳答案
当您返回初始 View Controller 时,您不需要再次获取数据。只需使用 ViewWillAppear
方法。获取 celloffset
并滚动 TableView 。
let celloffset = UserDefaults.standard.integer(forKey: "celloffset")
if celloffset != 0{
let index = IndexPath(item: celloffset, section: 0)
self.tableView.scrollToRow(at: index, at: UITableViewScrollPosition.middle, animated: false)}
关于ios - UITableView 导航后滚动到选定的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230895/