Reputation: 89
I have a UITableView with a random number of custom cells. It's working fine.
I am moving the selected cell to the top of the UITableView with:
tableView.scrollTo(index path animated)
However, when the selected cell is on the last full 'page' of cells, this doesn't work - obviously.
Can I make this work by somehow 'padding' out the table with empty space, dependent on the Y position of the selected cell, so that even selecting the last row, it would animate and move to the top of the table view?
I thought:
let point = CGPoint(x: 0, y: 200)
tableView.setContentOffset(point, animated: false)
would work, but it didn't (the 200) was a test amount.
I'm sure this is possible, could I please get a pointer?
Upvotes: 4
Views: 1450
Reputation: 89
rMaddy gave the right answer. Thanks so much! I'd never have thought of using the footer!
Just for those that might be interested here was the working code:
NOTE, that it's just a prototype, so I'm hard coding number of cells and how many can be visible on screen at once.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let maxNumberOfRows = 24
let maxNumberOfVisibleRows = 10
let safeArea: CGFloat = 20
let cell = tableView.cellForRow(at: indexPath)
if indexPath.row >= maxNumberOfRows - maxNumberOfVisibleRows
{
let numberOfSpacesRequired = ( maxNumberOfRows - indexPath.row ) * Int((cell?.bounds.height)!)
let spaceView = UIView()
spaceView.bounds = CGRect(x: 0, y: 0, width: Int(tableView.bounds.width), height: ( Int(tableView.bounds.height - safeArea) - numberOfSpacesRequired) )
tableView.tableFooterView = spaceView
}
tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
}
Upvotes: 1
Reputation: 318774
If you want to allow a table view to be scrolled far enough for the last row to reach the top of the screen, set a view as the table view's tableFooterView
.
Make it an empty UIView
with a height that is equal to the visible height of the table view minus the height of one row.
Upvotes: 2