简体   繁体   English

当用户使用后退按钮到UITableView滚动到最后选择的行时

[英]When user uses back button to UITableView to scroll to last selected row

I have a tableView with about 200 rows. 我有一个约200行的tableView。 When a user selects a row to view the details and later hits the back button, the tableView always returns to the top of the table. 当用户选择一行以查看详细信息并随后单击“后退”按钮时,tableView始终返回到表的顶部。

I would like to set up the tableView to force the tableView to auto scroll to the row in which the user last selected. 我想设置tableView来强制tableView自动滚动到用户最后一次选择的行。

How to do this? 这个怎么做?

you called any webservice call or reloadData in viewWillAppear , or viewDidAppear just remove that webservicecall/reloadData from viewWillAppear , or viewDidAppear automatically it shows last selected cell in tableview. 您在viewWillAppear中调用了任何webservice调用或reloadData ,或者viewDidAppear只是从viewWillAppear中删除了该webservicecall / reloadData,或者viewDidAppear会自动在表视图中显示最后选择的单元格。

or the alternate Way 或替代方式

savedScrollPosition means save your selected Index on didselectRow savedScrollPosition意味着将您选择的索引保存在didselectRow上

yourTableView.scrollToRow(at: IndexPath(row: savedScrollPosition, section: 0), atScrollPosition: .top, animated: false)
var point = yourTableView.contentOffset
point.y -= yourTableView.rowHeight
yourTableView.contentOffset = point

I would suggest storing selected NSIndexPath in the didSelectRowAtIndexPath method (when user presses on a cell). 我建议将选定的NSIndexPath存储在didSelectRowAtIndexPath方法中(当用户按下单元格时)。 Then in viewWillAppear or viewDidAppear method (in view controller where your table view is) just call 然后在viewWillAppearviewDidAppear方法(在您的表视图所在的视图控制器中)中调用

tableView.scrollToRow(at: selectedIndexPath, at: .top, animated: true)

It will then scroll your table view to previously selected cell. 然后它将表格视图滚动到先前选择的单元格。

Save the last seleted row in NSUserDefaults and use UITableView "scrollToRowAtIndexPath" as follows: 在NSUserDefaults中保存最后一个选定的行,并使用UITableView“ scrollToRowAtIndexPath”,如下所示:

Objective- C: 目标-C:

[self.tableView scrollToRowAtIndexPath:lastSelectedIndex atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

Swift: 迅速:

self.tableView.scrollToRowAtIndexPath(lastSelectedIndex, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)

Use this after UITableView is reloaded. 重新加载UITableView之后使用此方法。

I think you should find out what cause the table scroll to top. 我认为您应该找出导致表格滚动到顶部的原因。 Also You can save the selected indexPath to scroll to the row in which the user last selected. 另外,您可以保存选定的indexPath来滚动到用户最后一次选择的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM