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

Ios 如何在UITableView中滚动到最后一节的最后一行?,ios,swift,uitableview,Ios,Swift,Uitableview,所以我有一个UITableView,它从一个对象数组中获取数据,比如说Chats。要滚动到此数组的最后一行,我知道我们使用: var chats = [Chats]() self.tableView.scrollToRow(at: [0, self.chats.count - 1], at: .bottom, animated: true) 如果我有一个数组(这样我就可以根据日期将聊天信息分组到多个部分),该怎么办。现在我有部分,然后在该部分下有行 var groupedChats = [[C

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

var chats = [Chats]()
self.tableView.scrollToRow(at: [0, self.chats.count - 1], at: .bottom, animated: true)
如果我有一个数组(这样我就可以根据日期将聊天信息分组到多个部分),该怎么办。现在我有部分,然后在该部分下有行

var groupedChats = [[Chats]]()
如何滚动到最后一节的最后一行?

试试这个

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


查找最后一节和最后一行,并滚动到最后一行

Swift 5:

let lastSection = tableView.numberOfSections - 1
let lastRow = tableView!.numberOfRows(inSection: lastSection)
let lastRowIndexPath = IndexPath(row: lastRow, section: lastSection)
tableView.scrollToRow(at: lastRowIndexPath, at: .top, animated: true)
你可以试试这个

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)

更好地创建可重用性扩展:

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