2016-09-29 72 views
0

我想從UICollectionview刪除單元格,當用戶touchUpInside(Button)刪除單元格時。如何從集合視圖中刪除單元格?

這裏是我的代碼:

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() 
} 

我哪裏做錯了嗎?您deletebutton用於獲取當前單元格

回答

-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 
    let i : Int = (sender.layer.value(forKey: "Cdelete")) as! Int 
self.items.remove(at: i) 
collectionView.reloadData() 

} 
+0

謝謝你的回答,但鋼得到錯誤 意外發現零同時展開一個可選值... 線程1:EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,子代碼= 0x0) – seggy

+0

其中你遇到這個問題的那行 –

+0

在這一行中collectionView.reloadD ata() – seggy

相關問題