![](/img/trans.png)
[英]UIButton does not appear at last row of last section in UItableView
[英]How to scroll to last row of the last section in a UITableView?
所以我有一個 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)
}
查找最后一節和最后一行,並滾動到索引路徑的最后一行。
斯威夫特 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)
}
}
}
更好地創建可重用性的擴展:
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)
}
}
}
你可以試試這個,
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.