我在 UICollectionView 单元格中使用按钮,我想按钮可以改变颜色只有两个索引,如果单击其他按钮则不能改变颜色 uicolor.clear
我想要这样,那么如何使用sender.backgroundColor
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
}
}
}
最佳答案
我会这样做:
- 使用自定义 UICollectionViewCell 子类(没有按钮,因为 Collection View 单元会自行处理选择)
在此单元格类中重写
isSelected
属性,如下所示:override var isSelected: Bool { didSet { // set color according to state self.backgroundColor = self.isSelected ? .blue : .clear } }
在控制您的
collectionView
的类中执行collectionView.allowsMultipleSelection = true
在您的
UICollectionViewDelegate
实现方法中(这将防止一次选择两个以上的单元格):func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return (collectionView.indexPathsForSelectedItems?.count ?? 0) < 2 }
这样您就不需要单元格内的按钮。
关于ios - 如果只能选择两个,如何更改 UiCollectionView 中单元格的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52177160/