UITableview只滚动到中间 - Swift 4

时间:2017-10-15 07:55:48

标签: ios uitableview scroll swift4

我有一个包含聊天消息的表格视图。我试图滚动到tableview的底部,但它只向中间滚动。我怀疑这与不同高度的细胞有关(因为有些消息比其他消息长)。

有没有办法完全滚动到底部而不是基于平均单元格高度?

以下是我用来滚动到底部的代码:

let lastIndex = IndexPath(row: messages.count - 1, section: 0)
self.tableview.scrollToRow(at: lastIndex, at: .bottom, animated: true)

1 个答案:

答案 0 :(得分:1)

使用TableView扩展程序

import UIKit

    extension UITableView {
        func scrollToBottom(animated: Bool) {
            let y = contentSize.height - frame.size.height
            setContentOffset(CGPoint(x: 0, y: (y<0) ? 0 : y), animated: animated)
        }
    }

<强>用法

tableView.scrollToBottom(animated: true)