【问题标题】:How to delete a Cell from Collection View?如何从集合视图中删除单元格?
【发布时间】:2016-09-29 07:25:55
【问题描述】:

当用户touchUpInside(Button) 删除单元格时,我想从UICollectionview 中删除单元格。

这是我的代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell

    cell.myLabel.text = self.items[indexPath.row]

    cell.deleteBtn?.layer.setValue(indexPath.row, forKey: "Cdelete")
    cell.deleteBtn?.addTarget(self, action: Selector(("deleteColor:")), for: UIControlEvents.touchUpInside)


    cell.backgroundColor = UIColor.cyan // make cell more visible in our example project

    return cell
}

func deleteColor(sender:UIButton) {

    let i : Int = (sender.layer.value(forKey: "Cdelete")) as! Int
    self.items.remove(at: i)
    collectionView.reloadData()
}

我哪里做错了?

【问题讨论】:

    标签: ios swift uicollectionview swift3


    【解决方案1】:

    为您的删除按钮设置标签以获取当前单元格/知道您点击了哪个单元格

    cell.deleteBtn?.tag = indexPath.row
    cell.deleteBtn?.addTarget(self, action: #selector(yourVCName. deleteColor(_:)), for: .touchUpInside)
    

    然后打电话

    @IBAction func deleteColor(_ sender: UIButton){
       print("Button pressed ? ")
      // continue your work
    
               var hitPoint = sender.convert(CGPoint.zero, to: yourCollectionViewName)
       var hitIndex: IndexPath? = yourCollectionViewName.indexPathForRow(at: hitPoint)
    
            self.items.remove(at: hitIndex.row)
              self.yourCollectionViewName.performBatchUpdates({
        self.yourCollectionViewName.deleteItems(at: [hitIndex])
    }) { (finished) in
        self.yourCollectionViewName.reloadItems(at: self.yourCollectionViewName.indexPathsForVisibleItems)
    }
    
     }
    

    【讨论】:

    • 感谢您的回答,但在展开可选值时,steel 意外发现 nil 错误...线程 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0)
    • 你在哪一行遇到了这个问题
    • 在这一行中collectionView.reloadData()
    • 我得到了解决方案,设置 collectionview 的出口是我的错误..Lol :-)
    • 调用collectionView.reloadData() 将不会显示所需的重新排列动画。您将不得不使用deleteItemsAtIndexPaths 方法。但是在这个方法之后,所有的按钮标签都要刷新以避免不一致。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多