Swift 5 从 CollectionView 中删除部分

标签 swift uicollectionview delete-row

我正在尝试让用户能够从聊天中删除消息,我正在使用基于 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/

相关文章:

Swift - 使用 for 循环读取嵌套结构

ios - 当我们关闭开关时,我们如何取消选择该行

ios - Swift:如何在设备旋转后刷新 UICollectionView 布局

ios - 如何打开事件并在选择 Collection View 单元格时传递变量?

c# - 删除行会破坏合并的单元格

swift - 在 Swift 中调度两个独立的异步线程

arrays - Swift - 从数组中修剪元素,将整数字符串转换为整数

ios - 我在 Tableview 单元格中有 collectionView。它总是返回零。我该如何解决?

sqlite - 根据具有多列键的另一个表删除行

swift - CoreData - 从 tableView 中删除行