在uicollectionview中快速插入一个单元格会给我一个错误

时间:2017-08-29 08:45:58

标签: ios swift

我有这段代码

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return comments.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = commentSection.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CommentCell
        return cell
}

我有以下功能,插入单元格

 DispatchQueue.main.async{
                    let indexPath = IndexPath(row: self.comments.count, section: 0)
                    self.commentSection.insertItems(at: [indexPath])
                    self.commentSection.reloadData()
 }

但每当我运行此代码时,它都会打印此错误

libc++abi.dylib: terminating with uncaught exception of type NSException

并将我重定向到AppDelegate文件。即使错误写得很清楚我也无法理解这个问题

4 个答案:

答案 0 :(得分:8)

您需要先从collectionView中的insertingdeleting单元格之前修改数据源。

self.collectionView?.performBatchUpdates({
    let indexPath = IndexPath(row: self.comments.count, section: 0)
    comments.append(your_object) //add your object to data source first
    self.collectionView?.insertItems(at: [indexPath])
}, completion: nil)

答案 1 :(得分:0)

在将项目插入集合视图之前,请确保在comments数组中插入其他对象

答案 2 :(得分:0)

performBatchUpdates是在collectionView中插入项目的推荐方法。首先更新数据源,然后调用performBatchUpdates以在集合视图中插入新项目。

 //Update DataSource
 let newComment = "This is new comment"
 comments.append(newComment)

let indexPath = IndexPath(item: self.comments.count - 1, section: 0)
var indexPaths: [IndexPath] = [indexPath]

// finally update the collection view
collectionView.performBatchUpdates({ () -> Void in
    collectionView.insertItems(at: indexPaths)
}, completion: nil)

答案 3 :(得分:0)

SWIFT 4

onMain {


            CATransaction.begin()
            CATransaction.setDisableActions(true)

            self.chatData.append(res)

            let indexPath = IndexPath(row: self.chatData.count - 1, section: 0)

            self.collectionView?.insertItems(at: [indexPath])

            CATransaction.commit()

            print("scroll to index path: \(indexPath)")

            self.collectionView.scrollToItem(at: indexPath, at: .bottom , animated: true)

            //self.collectionView.scrollToMaxContentOffset(animated: true, newHeight: 100)

        }