Rutger Huijsmans Rutger Huijsmans - 3 months ago 23
iOS Question

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.

Answer

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.

let scrollPoint = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.frame.size.height)
self.tableView.setContentOffset(scrollPoint, animated: true)



It was a combination of answers. I ended up doing this:

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)
    })
}

Added this to my UITableViewDelegate :

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

Added this to the bottom of my .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)
        }
    }
}
Comments