Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift inserting a cell in uicollectionview gives me an error

Tags:

ios

swift

I have got this code

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
}

And i have functions below this which inserts cells

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

But whenever i run this code it prints this error

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

And redirects me to AppDelegate file.Even though the error is very clearly written i can't understand the problem

like image 911
loUIS CK Avatar asked Aug 29 '17 08:08

loUIS CK


2 Answers

You need to modify the data source first before inserting or deleting a cell from collectionView.

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)
like image 191
Sandeep Bhandari Avatar answered Nov 10 '22 00:11

Sandeep Bhandari


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)

        }
like image 40
Sachin Rasane Avatar answered Nov 10 '22 01:11

Sachin Rasane