[英]Ambiguous reference to member 'tableView(_:numberOfRowsInSection:)' Why this error?
[英]Why tableview numberOfRowsInSection is not updating after insertRows executed?
我正在使用帶有TableView.transform = CGAffineTransform (scaleX: 1,y: -1)
反向tableViewCell
和反向tableViewCell
,並使用insertRows
和deleteRows
方法對其進行更新。 如果在tableView
的可見區域中進行了插入和刪除操作,則tableView
可以正常工作。 如果未在可見區域中完成更新方法,則會崩潰。
func insertEntries(){
if itemsToInsert.count == 0{
return
}
let entry = itemsToInsert.first
itemsToInsert.removeFirst()
dataArray.append(entry!)
let indexPath = IndexPath(row: 0, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: UITableView.RowAnimation.bottom)
tableView.endUpdates()
insertEntries()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
錯誤是:
更新之后(50),現有節中包含的行數必須等於更新(47)之前,該節中包含的行數,加上或減去從該節中插入或刪除的行數(已插入1) ,刪除0個),然后加上或減去移入或移出該部分的行數(移入0,移出0)。
謝謝
您需要在tableView.beginUpdates()
和tableView.endUpdates()
之間執行模型更新,僅在那里進行tableView
更新可能會導致問題。
另外,您要插入行的索引與插入項目的索引不匹配。 您將追加到dataArray
的末尾,但要插入IndexPath(row: 0, section:0)
您能檢查一下是否解決了您的問題?
func insertEntries(){
if itemsToInsert.count == 0{
return
}
let entry = itemsToInsert.first
itemsToInsert.removeFirst()
let indexPath = IndexPath(row: 0, section: 0)
tableView.beginUpdates()
dataArray.insert(entry!, at: 0)
tableView.insertRows(at: [indexPath], with: UITableView.RowAnimation.bottom)
tableView.endUpdates()
insertEntries()
}
按原樣,您的代碼實際上並不會執行多個動畫,因為所有動畫實際上都是在同一時間創建的。
但是,該代碼應在理論上起作用。 但是實際上,在UITableView
實現中有一些奇怪的事情使類似的事情很難執行,而對於沒有這些問題的UICollectionView
則要容易得多。
還要注意,您要追加一個項目,但是要插入第一行。 這顯然是不正確的。
修復代碼的一種方法是在上一個動畫結束之前才觸發動畫,這可能是您真正想做的:
func insertEntries(){
guard !itemsToInsert.isEmpty else {
return
}
let entry = itemsToInsert.removeFirst()
dataArray.append(entry)
let indexPath = IndexPath(row: dataArray.count - 1, section: 0)
tableView.beginUpdates()
CATransaction.setCompletionBlock { [weak self] in
self?.insertEntries()
}
tableView.insertRows(at: [indexPath], with: .bottom)
tableView.endUpdates()
}
如果您不希望對一行進行動畫處理,這可能需要花費大量時間處理多個項目,所以我可以簡化為:
func insertEntries(){
guard !itemsToInsert.isEmpty else {
return
}
dataArray.append(contentsOf: itemsToInsert)
let numItems = itemsToInsert.count
itemsToInsert = []
let addedRows = Array((dataArray.count - numItems) ..< dataArray.count)
.map { IndexPath(row: $0, section: 0 })
tableView.beginUpdates()
tableView.insertRows(at: addedRows, with: .bottom)
tableView.endUpdates()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.