所以我有一个UITableView,它从一个对象数组(如聊天)中获取数据。要滚动到该数组的最后一行,我知道我们使用:
var chats = [Chats]()
self.tableView.scrollToRow(at: [0, self.chats.count - 1], at: .bottom, animated: true)
如果我有一个数组数组怎么办(这样我就可以根据日期将聊天消息分组为多个部分)。现在,我有几节,然后是该节下的行。
var groupedChats = [[Chats]]()
如何滚动到上一节的最后一行?
答案 0 :(得分:2)
尝试一下
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)
}
答案 1 :(得分:1)
找到最后一部分和最后一行,并滚动到最后一行索引路径。
快捷键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)
答案 2 :(得分:1)
更好地创建可重用性扩展:
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)
}
}
}
答案 3 :(得分:0)
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)
}
}
}
答案 4 :(得分:0)
您可以尝试一下
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)