我想要做的是,当我点击单元格中的按钮时,该单元格中的按钮将变得不可见。问题是当我点击按钮时,它变得不可见,但是当我滚动 Collection View 时,隐藏的按钮从一个按钮转到另一个按钮。例如,我点击它隐藏的第二个,但是当我滚动时,我看到第 7 个被隐藏了。每次滚动隐藏按钮时都会发生变化。
这是我写的代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : CollectionViewCellKharid3 = collectionView.dequeueReusableCell(withReuseIdentifier: "customcell3", for: indexPath) as! CollectionViewCellKharid3
cell.lblEsmeMahsul.text = mainCats[indexPath.row]
cell.imgMahsul.af_setImage(withURL: URL(string : (mainadress + "/Opitures/" + mainPicNumbers[indexPath.row]))!, placeholderImage: UIImage(named: "loadings" ))
cell.btnKharid.addTarget(self, action: #selector(btnColectionviewCellTapped), for : UIControlEvents.touchUpInside)
cell.btnKharid.tag = indexPath.row
cell.btnMosbat.addTarget(self, action: #selector(btnMosbatTapped), for : UIControlEvents.touchUpInside)
cell.btnMosbat.tag = indexPath.row
cell.configureCell()
return cell
}
@objc func btnColectionviewCellTapped(_ sender:UIButton){
// let indexPath : IndexPath = self.collectionview1.ind
print(sender.tag)
sender.isHidden = true
}
@objc func btnMosbatTapped(_ sender:UIButton){
let index = IndexPath(item: sender.tag , section: 0)
let cell = self.collectionviewForushVije.cellForItem(at: index) as? CollectionViewCellKharid3
cell?.lblTedad.text = "22"
print(sender.tag)
}
最佳答案
细胞得到重用。您需要跟踪哪些单元格已被点击,以便您可以在 cellForItemAt
方法中设置正确的按钮状态。
在你的类中声明一个属性:
var beenTapped: Set<Int> = []
然后在 btnColectionviewCellTapped
添加:
beenTapped.insert(sender.tag)
在 cellForItemAt
中,您需要:
cell.btnKharid.isHidden = beenTapped.contains(indexPath.item)
您还应该将 indexPath.row
的使用替换为 indexPath.item
。 row
用于 TableView 。 item
用于 Collection View 。
关于ios - 仅更改一个 collectionview 单元格的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078216/