我的收藏夹视图有多个部分。我想要达到的目的是,用户只能在每个部分中选择一个单元格(答案)。选择单元格(答案)后,背景颜色将改变。
我没有做的是那个例子:当用户单击第1节中的一个单元格时,我只想取消选择第1节中的另一个单元格。
下面是我的一些代码
@IBOutlet var step3CollectionView: UICollectionView!
var HexColor = HexColorClass()
var dataPageThree : json_PageThree!
var step3AnswerArray : [Int] = []
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var frameCount = dataPageThree.step_instruction.first!.subquestions.count
for i in 0..<frameCount{
if indexPath.section == i {
step3AnswerArray[i] = (dataPageThree.step_instruction.first?.subquestions[i].subquestion_selection_answerNums![indexPath.row])!
let callCell = self.step3CollectionView.cellForItem(at: indexPath) as? Step3CollectionViewCell
callCell!.answerLabel.backgroundColor = HexColor.hexStringToUIColor(hex: "117577")
callCell!.answerLabel.textColor = UIColor.white
}
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
let indexPaths = collectionView.indexPathsForSelectedItems
if (indexPaths?.count) ?? 0 > 0 {
/// If you need simple way
for index in indexPaths! {
if index.section == indexPath.section {
self.step3CollectionView.deselectItem(at: index, animated: true) // if want deselect previous selection
let callCell = self.step3CollectionView.cellForItem(at: index) as? Step3CollectionViewCell
callCell!.answerLabel.backgroundColor = UIColor.white
callCell!.answerLabel.textColor = UIColor.black
//return false //if you do not want further selection
}
}
}
return true
}
需要一些指导。
override func viewDidLoad() {
super.viewDidLoad()
self.step3CollectionView.allowsMultipleSelection = true
}
现在,UICollectionViewDelegate
方法collectionView(_: shouldSelectItemAt:)
应该看起来像,
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
collectionView.indexPathsForSelectedItems?.filter({ $0.section == indexPath.section }).forEach({ collectionView.deselectItem(at: $0, animated: false) })
return true
}
此外,请勿基于backgroundColour
选择更改cell
或shouldSelectItemAt
中didSelectItemAt
的cell's
。这使得代码庞大且多余。
应该在UICollectionViewCell
子类中通过覆盖
isSelected
属性来完成。
class CollectionViewCell: UICollectionViewCell { override var isSelected: Bool { didSet { self.backgroundColor = isSelected ? .blue : .lightGray } } }