Search code examples
iosobjective-cxcodeuitableview

Scroll table view to bottom when using dynamic cell height


How can I scroll my table view to the bottom when using dynamic cell height?

For some reason this code does not work in this scenario:

[self.tableView scrollRectToVisible:CGRectMake(0, self.tableView.contentSize.height - self.tableView.bounds.size.height, self.tableView.bounds.size.width, self.tableView.bounds.size.height) animated:YES];

Thanks!

EDIT: Use @Hasiya's code to scroll to the bottom, for some of you that alone might do the trick.


Solution

  • Eventually, I have found the answer. The reason why scrolling to the bottom does not work (and inserting/deleting rows are buggy as well, as I found out later), is because cell height is not properly estimated. To get around this, try to return close estimations in estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath. However, if you can't do that (and in most cases you won't be able to) there is still a great solution: Store the heights of the cells in a dictionary, and return those for the estimatedHeight when cells are reused (e.g. table view is scrolled). I have found this solution in another question, so please go and check that out for the actual code on how you would carry this out. (although probably, many of you can write this for themselves)

    Original solution by @dosdos

    EDIT: Maybe to fix just scrolling to the bottom this is unnecessary, however highly recommended in my opinion. If you don't use this for estimating your row height, you will encounter other problems such as buggy scrolling and worse performance at a large number of cells.

    Also you need to add this to viewDidAppear

    let lastItem = IndexPath(item: dataSource.count - 1, section: 0)
    tableView.scrollToRow(at: lastItem, at: .bottom, animated: true)