Scroll down to the end of the UITableView

I have one UITableView, and I'm trying to load 36 lines into it, and then scroll all the way to the last cell.

I 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 halfway.

+4
source share
1 answer

If you need to scroll to the last cellof tableView, you can use it setContentOffsetso that you can scroll to the last cell 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 with 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)
        }
    }
}
+7
source

Source: https://habr.com/ru/post/1650861/


All Articles