[英]Swift UITableView - How to put new items on top not on the bottom of the list?
我是Swift的新人,關於UITableView的示例代碼顯示,新項目被放置在列表的底部。 我們怎樣才能扭轉這一局面? 我搜索了 inte.net 但找不到答案。
謝謝。 居文
UITableviews 根據數組的順序顯示數據,例如字符數組
var data = ["B","C","D","E"]
通常,您可以使用 append 將數據添加到數組中,它會將數據添加到數組的末尾,這就是為什么它將數據添加到列表底部的原因。
data.append("A")
如果您希望表視圖在列表頂部添加數據,那么您可以像這樣在數組的開頭添加數據。
data.insert("A", at: 0)
現在重新加載您的 tableView,新數據將添加到列表頂部
yourTableViewName.reloadData()
要將新項目放在頂部,請將其插入所需的 position(索引 0)並重新加載相應的 indexPath(行:0,部分:0)。
let indexPathOfFirstRow = NSIndexPath.init(forRow: 0, inSection: 0)
yourArray.insert("some element", atIndex: 0)
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([indexPathOfFirstRow], withRowAnimation: .Automatic)
tableView.endUpdates()
重新加載整個表是一項代價高昂的任務,不推薦這樣做。
將項目添加到數組的最后一個索引。 然后重新加載tableView
在 0 索引處的數據數組上插入新項目很容易,但保留 tableview 的 state 是很困難的,尤其是當你也在處理標題時......
在對聊天進行分頁時,我將其用於 append 條舊消息...
您可以使用data.insert("new message", at: 0)
迭代數據並插入新項目和 header,但 tableview 會自動跳轉到零索引。 為了保留 state 你應該在每個新項目中都需要一個唯一的 ID 在我的例子中是time
和messageId
我在附加新項目之前保存最后一條消息 ID ...並使用該 ID 計算前一個頂部消息單元格的 indexPath 並滾動到它沒有 animation ...
func getIndexPath(WithMessageId id: Double) -> IndexPath? {
for (section, sectionObjects) in messagesArray.enumerated() {
if let index = sectionObjects.Messages?.firstIndex(where: { $0.MessageID == id }) {
return IndexPath(row: index, section: section)
}
}
return nil
}
此方法返回索引路徑使用如下
self.tableView.reloadData()
self.tableView.scrollToRow(at: getIndexPath(WithMessageId: lastMessageID) ?? IndexPath(row: 0, section: 0),
at: .top, animated: false)
它會 append 新項目甚至沒有任何故障,如 Twitter 在頂部附加新新聞提要......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.