ios - 仅更改一个 collectionview 单元格的对象

标签 ios swift uicollectionview

我想要做的是,当我点击单元格中的按钮时,该单元格中的按钮将变得不可见。问题是当我点击按钮时,它变得不可见,但是当我滚动 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)
}

enter image description here

最佳答案

细胞得到重用。您需要跟踪哪些单元格已被点击,以便您可以在 cellForItemAt 方法中设置正确的按钮状态。

在你的类中声明一个属性:

var beenTapped: Set<Int> = []

然后在 btnColectionviewCellTapped 添加:

beenTapped.insert(sender.tag)

cellForItemAt 中,您需要:

cell.btnKharid.isHidden = beenTapped.contains(indexPath.item)

您还应该将 indexPath.row 的使用替换为 indexPath.itemrow 用于 TableView 。 item 用于 Collection View 。

关于ios - 仅更改一个 collectionview 单元格的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078216/

相关文章:

ios - 如何打开iOS状态栏中的网络指示灯?

ios - 如何将选择器中的值附加到文本字段

ios - 类型 'ViewController' 的值没有成员 'authUI' ?

ios - Collection View 错误 : must pass a valid reuse identifier

ios - Swift UIPickerView 禁用组件

iOS 应用程序 - 更改版本号方案

swift - alamofire和URLSession中上传数据key,如何添加?

xcode - Xcode 文档注释的快捷方式

ios - 在 ViewDidLoad 中解析 UICollectionViewController 的查询

ios - 什么都不显示时如何在 Xcode 中自动隐藏 Collection View ?