iosswiftuitableview

Scroll all the way down to the bottom of UITableView


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.


Solution

  • 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: animated)
            }
        }
    }