9

I've a UITableView and I'm trying to load 36 rows into it and then scroll all the way down the last cell.

I've tried this:

func reloadData(){
    chatroomTableView.reloadData()
    chatroomTableView.scrollToBottom(true)
}


extension UITableView {
    func scrollToBottom(animated: Bool = true) {
        let sections = self.numberOfSections
        let rows = self.numberOfRowsInSection(sections - 1)
        if (rows > 0){
            self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true)
        }
    }
}

But it only scrolls down halfway.

RenniePet
  • 11,420
  • 7
  • 80
  • 106
Rutger Huijsmans
  • 2,330
  • 2
  • 30
  • 67
  • Does `rows` and `sections` have the expected value in your `scrollToBottom` function when it's called? – rmaddy Aug 11 '16 at 03:40
  • Yes, rows = 36 and sections = 1. Yet it only scrolls to row 10 of section 0. – Rutger Huijsmans Aug 11 '16 at 03:45
  • Try wrapping your call to `scrollToBottom` inside a `dispatch_async` or maybe `dispatch_after`. – rmaddy Aug 11 '16 at 03:49
  • With dispatch_async it will scroll down to row 24, with dispatch_after (2 sec) it scrolls to 22. Still not number 36 like I want it to. – Rutger Huijsmans Aug 11 '16 at 03:56
  • It would be better if you posted your solution as a separate answer instead of as an edit to Nirav D's answer - that makes his/your answer very confusing. And maybe explain why his answer wasn't sufficient for your needs. – RenniePet Feb 14 '17 at 14:46

1 Answers1

17

If your requirement is to scroll to the last cell of tableView you can use setContentOffset like this so that you can scroll to the last cell of tableView.

Put this in the reloadData() function:

func reloadData(){
    chatroomTableView.reloadData()
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        let scrollPoint = CGPoint(x: 0, y: self.chatroomTableView.contentSize.height - self.chatroomTableView.frame.size.height)
        self.chatroomTableView.setContentOffset(scrollPoint, animated: true)
    })
}

Add this to your UITableViewDelegate :

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let lastRowIndex = tableView.numberOfRowsInSection(0)
        if indexPath.row == lastRowIndex - 1 {
            tableView.scrollToBottom(true)
        }
    }

Add this to the bottom of your .swift file:

extension UITableView {
    func scrollToBottom(animated: Bool = true) {
        let sections = self.numberOfSections
        let rows = self.numberOfRowsInSection(sections - 1)
        if (rows > 0){
            self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true)
        }
    }
}
Rutger Huijsmans
  • 2,330
  • 2
  • 30
  • 67
Nirav D
  • 71,513
  • 12
  • 161
  • 183