滚动到UITableView的底部

9

我有一个UITableView,我正在尝试将36行加载到其中,然后滚动到最后一个单元格。

我尝试了以下方法:

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

但它只能滚动一半。

当调用scrollToBottom函数时,rowssections是否具有预期值? - rmaddy
是的,行数为36,节数为1。但它只滚动到第0节的第10行。 - Rutger Huijsmans
尝试将对 scrollToBottom 的调用包装在 dispatch_async 或者 dispatch_after 中。 - rmaddy
使用dispatch_async,它会滚动到第24行;使用dispatch_after(2秒),它会滚动到第22行。但仍然不是我想要的第36行。 - Rutger Huijsmans
最好你将你的解决方案发布为一个单独的回答,而不是作为对Nirav D回答的编辑 - 这会让他/你的答案变得非常混乱。或者解释一下为什么他的答案不能满足你的需求。 - RenniePet
1个回答

17

如果您的要求是滚动到tableView的最后一个cell,您可以像这样使用setContentOffset,以便您可以滚动到tableView的最后一个单元格。

将此放入reloadData()函数中:

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

将此添加到您的 UITableViewDelegate 中:

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

将以下代码添加到您的.swift文件底部:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接