一直向下滚动到UITableView的底部 [英] Scroll all the way down to the bottom of UITableView

查看:176
本文介绍了一直向下滚动到UITableView的底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我试过这个:

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.

推荐答案

如果您的要求是滚动到<的最后一个单元格 code> tableView 你可以像这样使用 setContentOffset 这样你就可以滚动到 tableView <的最后一个单元格/ code>。

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)




这是答案的组合。我最终这样做了:

把它放在reloadData()函数中:

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

将此添加到我的UITableViewDelegate:

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

将此添加到我的.swift文件的底部:

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

这篇关于一直向下滚动到UITableView的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆