2016-09-29 38 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

相关问题