我创建了一个包含 12 个单元格的 UICollectionView
。我想随时更改它们的颜色(更改为相同的颜色)。
这是我的代码:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)as! InterestCollectionViewCell
print("2 \(cell.interest) \(indexPath.row)")
if cell.selected == true {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.clearColor()
}
}
问题
- 再次点击时颜色不会变回
- 当我点击 [0] 单元格时,[5] 和 [10] 单元格也会改变颜色。同样在我点击 [1] 单元格后,[6] 和 [11] 单元格也被调用...等等。m
最佳答案
与其在 didSelectItemAtIndexPath
中设置颜色,不如在 cellForItemAtIndexPath
中设置颜色,为此您需要声明 Int
的实例并存储 的行code>collectionView
像这样在该实例中。
var selectedRow: Int = -1
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
// Set others detail of cell
if self.selectedRow == indexPath.item {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.clearColor()
}
return cell
}
现在在 didSelectItemAtIndexPath
中设置 selectedRow
重新加载 collectionView
。
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if self.selectedRow == indexPath.item {
self.selectedRow = -1
}
else {
self.selectedRow = indexPath.item
}
self.collectionView.reloadData()
}
编辑:对于多个单元格选择,创建一个 indexPath
数组并像这样存储 indexPath 的对象。
var selectedIndexPaths = [NSIndexPath]()
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
// Set others detail of cell
if self.selectedIndexPaths.contains(indexPath) {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.clearColor()
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if self.selectedIndexPaths.contains(indexPath) {
let index = self.selectedIndexPaths.indexOf(indexPath)
self.selectedIndexPaths.removeAtIndex(index)
}
else {
self.selectedIndexPaths.append(indexPath)
}
self.collectionView.reloadData()
}
关于ios - 多个 UICollectionViewCell 颜色一起更改问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577352/