问题
I have a tableView with about 200 rows. 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.
I would like to set up the tableView to force the tableView to auto scroll to the row in which the user last selected.
How to do this?
回答1:
I would suggest storing selected NSIndexPath
in the didSelectRowAtIndexPath
method (when user presses on a cell).
Then in viewWillAppear
or viewDidAppear
method (in view controller where your table view is) just call
tableView.scrollToRow(at: selectedIndexPath, at: .top, animated: true)
It will then scroll your table view to previously selected cell.
回答2:
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.
or the alternate Way
savedScrollPosition means save your selected Index on didselectRow
yourTableView.scrollToRow(at: IndexPath(row: savedScrollPosition, section: 0), atScrollPosition: .top, animated: false)
var point = yourTableView.contentOffset
point.y -= yourTableView.rowHeight
yourTableView.contentOffset = point
回答3:
Save the last seleted row in NSUserDefaults and use UITableView "scrollToRowAtIndexPath" as follows:
Objective- 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.
回答4:
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.
来源:https://stackoverflow.com/questions/40970176/when-user-uses-back-button-to-uitableview-to-scroll-to-last-selected-row