如何在要删除的单元格上使用 longtapGesture 从集合视图中删除 uicollectionviewcell?迅速

Posted

技术标签:

【中文标题】如何在要删除的单元格上使用 longtapGesture 从集合视图中删除 uicollectionviewcell?迅速【英文标题】:How can I delete a uicollectionviewcell from collection view using longtapGesture on the cell that I want to remove? swift 【发布时间】:2018-01-30 10:50:25 【问题描述】:

如何使用长按手势从集合视图中删除所选项目并显示重新加载的数据,因为我无法使用 indexpath.row 方法执行此操作。我正在使用 UIAlertAction 来实现此操作。但无法点击 longtapGesture 上的单元格。

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
        let mainstoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let detailVC = mainstoryboard.instantiateViewController(withIdentifier: "detailVC") as! DetailVC
        detailVC.image = Model.dataList[indexPath.item].image
        self.navigationController?.pushViewController(detailVC, animated: true)

        let tapGes = UILongPressGestureRecognizer(target: self, action: #selector(self.didlongPress(tapGes:)))
        self.view.addGestureRecognizer(tapGes)
    

//    func removeItem(index : Int)
//        Model.dataList.remove(at: index)
//        
//        let indexPath = IndexPath(row: index, section: 0)
//        collectionView.performBatchUpdates( 
//            self.collectionView.deleteItems(at: [indexPath])
//        )  (finished : Bool) in
//            self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems)
//        
//    
//    
//    


    func didlongPress(tapGes : UITapGestureRecognizer)
        let actionController = UIAlertController(title: "Delete", message: "Are You Sure ...?", preferredStyle: .actionSheet)

        let action = UIAlertAction(title: "Delete Current record", style: .default)  (action) in
            print("Deleted")

            self.collectionView.reloadData()
        

        actionController.addAction(action)
        self.present(actionController, animated: true, completion: nil)

    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CollectionCell
        let note = Model.dataList[indexPath.item]
        cell?.imageView.image = note.image
        cell?.titleLbl.text = note.title


        return cell!
    

【问题讨论】:

【参考方案1】:

嘿,下面的算法对你有用。

点击时只需从数组“数据列表”中删除该项目 indexPath 通过调用“datalist.remove(at: indexPath.row)”。 之后只需调用“self.collectionView.deleteItemsAtIndexPaths([indexPath])”。 这样您就不必重新加载collectionView。

祝你好运:)

【讨论】:

【参考方案2】:

@Daniyal 在您的 longpress 方法中获取 IndexPath,然后从索引处的数组中删除值。然后重新加载您的收藏视图。

【讨论】:

以上是关于如何在要删除的单元格上使用 longtapGesture 从集合视图中删除 uicollectionviewcell?迅速的主要内容,如果未能解决你的问题,请参考以下文章

如何在选择单元格上的 UIcollectionViewCell 特定单元格中删除长手势?

iOS - 如何查看表格视图单元格上的“滑动删除”操作?

在 WPF DataGrid 的单个单元格上设置删除线的最佳方法?

在uitableview单元格上留下滑动删除按钮打开然后返回导致崩溃

如何在原型单元格上使用 UITableView 单元格及其元素

表视图单元格上的情节提要约束以匹配页脚内容