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
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)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With