Skip to content

Instantly share code, notes, and snippets.

@zummenix
Created April 6, 2017 06:27
Show Gist options
  • Save zummenix/b654f46f7f1aed7d46204820f7125530 to your computer and use it in GitHub Desktop.
Save zummenix/b654f46f7f1aed7d46204820f7125530 to your computer and use it in GitHub Desktop.
Scroll to bottom for table views with dynamic sized cells
/// Scrolls to the bottom of the table view, typically used to skip content.
///
/// For precise scrolling please use `scrollToBottom(animated:)`.
fileprivate func initialScrollToBottom() {
if tableView.contentSize.height >= tableView.bounds.size.height {
tableView.contentOffset.y = tableView.contentSize.height - tableView.bounds.size.height
}
}
/// Scrolls to the bottom of the table view.
///
/// This method performs `reloadData()` on table view for precise scrolling.
/// Please use `initialScrollToBottom()` to skip initial content on the top of the table view.
///
/// - Parameter animated: Whether use animation or not.
fileprivate func scrollToBottom(animated: Bool) {
tableView.reloadData() // Allows us to use correct content size.
DispatchQueue.main.async {
if self.tableView.contentSize.height >= self.tableView.bounds.size.height {
let update = {
self.tableView.contentOffset.y = self.tableView.contentSize.height - self.tableView.bounds.size.height
}
if animated {
UIView.animate(withDuration: 0.2, animations: update)
} else {
update()
}
}
}
}
@zummenix
Copy link
Author

After testing this more I've realized it doesn't work correctly in all cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment