ios 如何在UITableView中滚动到最后一节的最后一行?

2admgd59  于 2023-07-01  发布在  iOS
关注(0)|答案(5)|浏览(150)

所以我有一个UITableView,它从一个对象数组中获取数据,比如Chats。要滚动到这个数组的最后一行,我知道我们用途:

var chats = [Chats]()
self.tableView.scrollToRow(at: [0, self.chats.count - 1], at: .bottom, animated: true)

如果我有一个数组的数组(这是为了让我可以分组聊天消息到基于日期的部分)。现在我有部分,然后在该部分下有行。

var groupedChats = [[Chats]]()

如何滚动到最后一节的最后一行?

euoag5mw

euoag5mw1#

查找最后一节和最后一行,并滚动到最后一行索引路径。

Swift 5:

let lastSection = tableView.numberOfSections - 1
let lastRow = tableView!.numberOfRows(inSection: lastSection) - 1
let lastRowIndexPath = IndexPath(row: lastRow, section: lastSection)
tableView.scrollToRow(at: lastRowIndexPath, at: .top, animated: true)
qaxu7uf2

qaxu7uf22#

试试这个

let lastSection = groupedChats.count-1
    let lastRow = groupedChats[lastSection].count-1
    if lastSection >= 0, lastRow >= 0 {
        self.tableView.scrollToRow(at: IndexPath(row: lastRow, section: lastSection), at: .bottom, animated: true)
    }
0lvr5msh

0lvr5msh3#

func scrollToBottom(_ animated: Bool = true) {
        let numberOfSections = self.tblView.numberOfSections
        if numberOfSections > 0 {
            let numberOfRows = self.tblView.numberOfRows(inSection: numberOfSections - 1)
            if numberOfRows > 0 {
                let indexPath = IndexPath(row: numberOfRows - 1, section: (numberOfSections - 1))
                self.tblView.scrollToRow(at: indexPath, at: .bottom, animated: animated)
            }
        }
    }
n53p2ov0

n53p2ov04#

最好创建一个可重用的扩展:

extension UITableView {

    func scrollToBottom(){

        DispatchQueue.main.async {
            let indexPath = IndexPath(
                row: self.numberOfRows(inSection:  self.numberOfSections-1) - 1,
                section: self.numberOfSections-1)
            self.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
}
9nvpjoqh

9nvpjoqh5#

你可以试试这个

let lastSectionIndex = self.groupedChats.numberOfSections - 1 // last section
let lastRowIndex = self.groupedChats.numberOfRows(inSection: lastSectionIndex) - 1 // last row
self.tableView.scrollToRow(at: IndexPath(row: lastRowIndex, section: lastSectionIndex), at: .Bottom, animated: true)

相关问题