我正在尝试让用户能够从聊天中删除消息,我正在使用基于 CollectionView 库的 MessageKit 部分。我试图通过长按删除部分。我做错了什么?
我收到此错误
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 0 from section 1, but there are only 1 sections before the update'
长按
@objc func longPressed(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let touchPoint = sender.location(in: self.messagesCollectionView)
if let indexPath = messagesCollectionView.indexPathForItem(at: touchPoint){
//indexPath.row = 0
//indexPath.section = 1
//row always is 0, and section +1 for every next message
messageList.remove(at: indexPath.section)
collectionView.performBatchUpdates({
collectionView.deleteItems(at: [indexPath])
collectionView.reloadData()
}, completion: nil)
}
}
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
return messageList.count
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
return messageList[indexPath.section]
}
最佳答案
像这样更新您的代码:
if let indexPath = messagesCollectionView.indexPathForItem(at: touchPoint){
//indexPath.row = 0
//indexPath.section = 1
//row always is 0, and section +1 for every next message
messageList.remove(at: indexPath.section)
collectionView.reloadData()
}
从数组中删除消息后重新加载 Collection View 。
希望这有帮助。
关于Swift 5 从 CollectionView 中删除部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505620/