UICollectionView重用单元格背景问题

时间:2017-06-29 07:53:42

标签: ios swift uicollectionview

我使用UICollectionview呈现4个按钮,用户应该选择1个按钮。 我创建了 uibutton的自定义子类

class CustomButton: UIButton {

    override var isSelected: Bool{
        didSet{
            backgroundColor =  isSelected ? Constants.Colors.selectedMenu: Constants.Colors.menuCell
        }
    }

}

自定义单元格类:

class SymptomCell: UICollectionViewCell {

    @IBOutlet weak var optionButton1: UIButton!
    @IBOutlet weak var optionButton2: UIButton!
    @IBOutlet weak var optionButton3: UIButton!
    @IBOutlet weak var optionButton4: UIButton!


    func configCell(options :  [String]){
        optionButton1.setTitle(options[0], for: .normal)
        optionButton2.setTitle(options[1], for: .normal)
        optionButton3.setTitle(options[2], for: .normal)
        optionButton4.setTitle(options[3], for: .normal)
    }

    @IBAction func clickAction(_ sender: UIButton) {
         sender.isSelected = sender.isSelected ? false : true
    }
}

我看到了例如,如果我选择按钮并滚动几个单元格,那么即使我没有按下它,同一索引中的按钮也会获得不同的背景颜色。

enter image description here

在我尝试使用的单元格类中:

 override func prepareForReuse() {
        optionButton1.isSelected = false
        optionButton2.isSelected = false
       // ...
 }

但每次都会取消选择所有项目。 我该怎么办?

2 个答案:

答案 0 :(得分:2)

UIView内的任何UICollectionViewCell必须在单元格重用之间无状态,因此,您必须保留prepareForReuse函数。

但是,UICollectionViewCell本身在以前选择的isSelected重用时会恢复其indexPath状态。

因此,方法可以是与按钮一起选择单元格。 你的单元格应该是这样的:

protocol MyCellDelegate : NSObjectProtocol {
    func optionButton1DidToggle(in cell: UICollectionViewCell?)
}

class MyCell: UICollectionViewCell {

    var delegate : MyCellDelegate?

    @IBAction func clickAction(_ sender: UIButton) {
        // you can assign delegate to your cell, the same as UICollectionViewDelegate, and forward here click callback to your delegate,
        delegate?.optionButton1DidToggle(in: self) 
        //.....
    }

    override var isSelected: Bool {
        didSet{
            optionButton1.isSelected = self.isSelected
        }
    }

    override func prepareForReuse() {
        optionButton1.isSelected = false
    }
}

MyCellDelegate实施:

public func optionButton1DidToggle(in cell: UICollectionViewCell?) {
    if !cell.optionButton1.isSelected {
        collectionView.selectItem(at: collectionView.indexPath(for: cell) animated:false scrollPosition:.centeredHorizontally)
    } else {
        collectionView.deselectItem(at: collectionView.indexPath(for: cell) animated:false)
    }
}

答案 1 :(得分:-1)

尝试在自定义单元格中使用prepareForReuse并设置backgroundColor = nil

override func prepareForReuse() {

    backgroundColor =  nil
    optionButton1.isSelected = false
}
相关问题