我创建了一个包含UIButton的自定义collectionView单元类。因此,每个单元格都包含一个用户可以按下的按钮。但是,只要轻按一个单元格按钮,就会导致其他单元格中按钮的背景颜色发生变化。我希望它只更改所选按钮的背景色,以防止更改为其他按钮。下面是我的代码:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! SubjectsCell
cell.subjectButton.setTitle(subjectNames[indexPath.row], for: .normal)
cell.subjectButton.addTarget(self, action: #selector(updateBackgroundColor(_:)), for: .touchUpInside)
if cell.subjectButton.isChosen == selectedState{
cell.subjectButton.backgroundColor = .green }
else if cell.subjectButton.isChosen != selectedState {
cell.subjectButton.backgroundColor = UIColor(red: 34.0/255.0, green: 210.0/255.0, blue: 255.0/255.0, alpha: 1)
}
return cell
[我意识到dequeueReusableCell会导致某些单元格被重用,如果这是我的问题,我如何防止随机单元格发生单元格更改,而仅影响点击按钮所在的单元格。
您是对的,dequeueReusableCell(withReuseIdentifier:for:)
是问题的根源!您只需要让您的单元格类覆盖UICollectionReusableView
的prepareForReuse()
方法,并将背景重置为所需的背景即可。
您可能需要更改数据模型,因此您可以记住哪些单元格按下了按钮,因为这些单元格不能保留该数据而不会引起问题。
还请注意,在addTarget
中调用collectionView(_:cellForItemAt:)
可能会在以后引起问题,通常在最初设置对象时仅将目标添加一次。为避免出现问题,您应该在笔尖/情节提要中将其设置为动作,或者在进行编程视图设置时设置视图对象时使用。
你可以做这样的事情
class SubjectsCell : UICollectionViewCell
{
@IBAction func buttonAction(_ sender: UIButton) {
updateBackgroundColor()
}
}
所以单元格视图背景更新应该出现在SubjectsCell中,因为它的视图更新不在viewController的工作中。