快速集合视图单元格内的按钮操作

时间:2021-01-28 15:04:06

标签: swift uicollectionview

在我的集合视图中有 6 个单元格。每个单元格都有一个按钮。如果我点击任何按钮,则按钮的图像将更改为刻度标记图像,所有其他单元格按钮将更改为取消标记图像。请任何人帮助我。我在这里添加了代码和图片。

在这张图片中,有一个tableview,在tableview单元格collectionview里面。

enter image description here

我的代码是:-

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InsuranceCollectionViewCell", for: indexPath) as? InsuranceCollectionViewCell else {
            return UICollectionViewCell()
        }
        cell.selectionButton.tag = indexPath.row
        let insuranceTypeAtIndex = insuranceTypeArray[indexPath.row]
        cell.insuranceTypeLabel.text = insuranceTypeAtIndex
        cell.selectionButton.addTarget(self, action: #selector(selectButtonAction(sender:)), for: .touchUpInside)
        return cell
    }


   @objc func selectButtonAction(sender: UIButton){
        let index = IndexPath(row: sender.tag, section: 0)
        let cell = insuranceTypeCollectionView.cellForItem(at: index) as? InsuranceCollectionViewCell
     
        
        if cell?.selectionButton.currentImage == UIImage(named: "untick"){
            cell?.selectionButton.setImage(UIImage(named: "tick"), for: .normal)
            print(cell?.insuranceTypeLabel.text)
        }
        else{
            cell?.selectionButton.setImage(UIImage(named: "untick"), for: .normal)
        }
    }

2 个答案:

答案 0 :(得分:0)

您为什么在集合视图中使用按钮。你应该在这里使用委托方法 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

在此委托中,您可以在用户单击时切换复选标记。

集合视图单元格应该是一个标签和一个模拟复选标记框的视图。

亲切的问候, MacUserT

答案 1 :(得分:0)

使用委托模式获取所选按钮的状态。

首先为collection view cell类创建一个协议(在改变visuals后调用selected button state的delegate方法)

然后,使表格视图单元格类符合该协议,并在集合视图的方法中将单元格中表格视图单元格类的委托设置为self

然后,如果您想在此表格视图单元格类中跟踪选定的集合视图项,请在此处保留一个变量,并在委托方法中设置该变量

如果要在实现表视图的类中获取数据,请对表视图执行相同的操作(为表视图单元格类创建协议,并在进行表视图实现的类中使其符合)。

>
相关问题