ios - 如果只能选择两个,如何更改 UiCollectionView 中单元格的颜色

标签 ios arrays swift button uicollectionviewcell

我在 UICollectionView 单元格中使用按钮,我想按钮可以改变颜色只有两个索引,如果单击其他按钮则不能改变颜色 uicolor.clear

enter image description here

我想要这样,那么如何使用sender.backgroundColor

enter image description here

func collectionView(_: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellB", for: indexPath) as! BandingCollectionViewCell

            cell.bBandingCell.addTarget(self, action: #selector(masterAction3(_:)), for: .touchUpInside)

        return cell
    }

{

@objc func masterAction3(_ sender: UIButton) {
        var indexPath = collectionView.indexPath(for: ((sender.superview?.superview) as! BandingCollectionViewCell))
        if sender.isSelected {
            sender.isSelected = false
            switch indexPath?.row {
            case 0:
                print("0")
                sender.backgroundColor = UIColor.clear
            case 1:
                print("1")
                sender.backgroundColor = UIColor.clear

            default:
                print("default")
                sender.backgroundColor = UIColor.blue
            }


        } else {
            sender.isSelected = true
            switch indexPath?.row {
            case 0:
                print("0")
                sender.backgroundColor = UIColor.blue
            case 1:
                print("1")
                sender.backgroundColor = UIColor.blue

            default:
                print("default")
                sender.backgroundColor = UIColor.clear
            }

        }

    }

最佳答案

我会这样做:

  1. 使用自定义 UICollectionViewCell 子类(没有按钮,因为 Collection View 单元会自行处理选择)
  2. 在此单元格类中重写 isSelected 属性,如下所示:

    override var isSelected: Bool {
        didSet {
            // set color according to state
            self.backgroundColor = self.isSelected ? .blue : .clear 
        }
    }
    
  3. 在控制您的collectionView 的类中执行collectionView.allowsMultipleSelection = true

  4. 在您的 UICollectionViewDelegate 实现方法中(这将防止一次选择两个以上的单元格):

    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return (collectionView.indexPathsForSelectedItems?.count ?? 0) < 2
    }
    

这样您就不需要单元格内的按钮。

关于ios - 如果只能选择两个,如何更改 UiCollectionView 中单元格的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52177160/

相关文章:

ios - 在 CoreData ios swift3 中仅获取表的几个属性

ios - 代码签名错误 : bundle format unrecognized, 无效,或不合适

ios - 如何关闭打开的 subview ?

c - 如何在 C 中将值从整数数组传递到带有空格的字符串数组

ios - 使用 Swift : Can't access all objects of an array after For loop 的数组问题

Swift Siesta 访问响应原始数据

ios - Swift Firebase UIRefreshControl

javascript - JavaScript 中的 Python any() 和 all() 函数等价于什么?

java - 将 Java 数组和基元 (double[][]) 重构为集合和泛型 (List<List<Double>>)

c - 将 swift 字符串传递给 c 函数 char *