簡體   English   中英

為什么執行insertRows后,tableview numberOfRowsInSection不更新?

[英]Why tableview numberOfRowsInSection is not updating after insertRows executed?

我正在使用帶有TableView.transform = CGAffineTransform (scaleX: 1,y: -1)反向tableViewCell和反向tableViewCell ,並使用insertRowsdeleteRows方法對其進行更新。 如果在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM