【问题标题】:Button action inside a collection view cell in swiftswift中集合视图单元格内的按钮操作
【发布时间】:2021-01-28 15:04:06
【问题描述】:

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

在这张图片中,有一个表格视图,在表格视图单元格内有一个集合视图。

我的代码是:-

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

【问题讨论】:

    标签: swift uicollectionview


    【解决方案1】:

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

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

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

    亲切的问候, Mac用户T

    【讨论】:

      【解决方案2】:

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

      首先,为collection view cell类创建一个协议(改变视觉效果后调用选中按钮状态的委托方法)

      然后,使表格视图单元格类符合该协议,并将委托设置为 self 以用于单元格中的表格视图单元格类,以便在集合视图的方法中获取项目

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

      如果你想在实现表视图的类中获取数据,对表视图执行相同的操作(为表视图单元类创建协议,并使类与表视图实现的类一致)。

      【讨论】:

        猜你喜欢
        • 2017-04-20
        • 2016-07-30
        • 1970-01-01
        • 1970-01-01
        • 2018-10-08
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多