[英]How to scroll to last row of the last section in a UITableView?
So I have a UITableView that fetches data from an array of an object say Chats .所以我有一个 UITableView 从对象数组中获取数据,比如Chats 。 To scroll to the last row of this array I know that we use:
要滚动到该数组的最后一行,我知道我们使用:
var chats = [Chats]()
self.tableView.scrollToRow(at: [0, self.chats.count - 1], at: .bottom, animated: true)
What if I have an array of array (This is so that I can group chat messages into sections based on date).如果我有一个数组怎么办(这样我就可以根据日期将聊天消息分组)。 Now I have sections and then rows under that section.
现在我有部分,然后是该部分下的行。
var groupedChats = [[Chats]]()
How do I scroll to the last row of the last section?如何滚动到最后一节的最后一行?
Try this试试这个
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)
}
Finding the last section and last row, and scroll to last rows indexpath.查找最后一节和最后一行,并滚动到索引路径的最后一行。
Swift 5:斯威夫特 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)
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)
}
}
}
Better create an extension for reusability:更好地创建可重用性的扩展:
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)
}
}
}
You can try this,你可以试试这个,
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.