Although that’s something that appears fairly easy, the truth -for me at least-, is that scrolling a UITableView to a specific cell every time you load it may prove tricky.
In the app I’m working on I implement it in the following way: every time a view appeared I assess if the top visible row is the one it should. If it is, no action is taken, else we’ll scroll to the right row.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Check if we need to scroll to a specific cell
if getTopVisibleRow() != getTableLastViewedTopPosition() {
tableView.scrollToRow(at: IndexPath(row: getTableLastViewedTopPosition(), section: 0), at: .top, animated: false)
}
}
For reference here’s what I’m doing in the getTopVisibleRow(), note that is is important only if you’re using a translucid navbar:
func getTopVisibleRow () -> Int {
//We need this to accounts for the translucency below the nav bar
let navBar = navigationController?.navigationBar
let whereIsNavBarInTableView = tableView.convert(navBar!.bounds, from: navBar)
let pointWhereNavBarEnds = CGPoint(x: 0, y: whereIsNavBarInTableView.origin.y + whereIsNavBarInTableView.size.height + 1)
let accurateIndexPath = tableView.indexPathForRow(at: pointWhereNavBarEnds)
return accurateIndexPath?.row ?? 0
}
For getTableLastViewedTopPosition() I’m simply fetching from the model what cell index should we be showing.
Questions / comments? I’m at @MarcMasVi
Marc