UICollectionView单元格没有正确高亮显示



我试图添加选择多个集合视图单元格的操作,并在选择单元格时更改背景颜色。当单元格被取消选中时,我还想将背景颜色更改回原始颜色。但是,当我滚动集合视图时,背景颜色改变的单元格消失了。我怀疑我可能需要跟踪indexPath。行,并将其保存到一个数组,但我不确定如何正确实现这一点。

var indexArray = [Int]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShoeCell", for: indexPath) as! ShoeSizesCell
cell.backgroundColor = UIColor.textFieldBackgroundColorGray
cell.shoeSize.textColor = UIColor.init(hexString: "#737373")

return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//    indexArray.append(indexPath.row)
if let currentCell = collectionView.cellForItem(at: indexPath) as? ShoeSizesCell {
if currentCell.backgroundColor == UIColor.textFieldBackgroundColorGray {
currentCell.backgroundColor = .primaryColor
currentCell.shoeSize.textColor = .white
}
else  if currentCell.backgroundColor == .primaryColor {
currentCell.backgroundColor = UIColor.textFieldBackgroundColorGray
currentCell.shoeSize.textColor = UIColor.init(hexString: "#737373")
}
}
}

当您在单元格中显示一些数据时,您可以为它创建一个模型。

struct Shoe {
let size: String
var isSelected: Bool
}

ShoeSizesCell中添加Shoe类型变量。覆盖UICollectionViewCellisSelected属性

class ShoeSizesCell: UICollectionViewCell {
var shoe: Shoe? {
didSet {
guard let shoe = shoe else { return }
self.shoeSize?.text = shoe.size
if shoe.isSelected {
self.backgroundColor = .primaryColor
self.shoeSize.textColor = .white
}
else {
self.backgroundColor = UIColor.textFieldBackgroundColorGray
self.shoeSize.textColor = UIColor.init(hexString: "#737373")
}
}
}

override var isSelected: Bool {
didSet {
if self.isSelected {
self.backgroundColor = .primaryColor
self.shoeSize.textColor = .white
}
else {
self.backgroundColor = UIColor.textFieldBackgroundColorGray
self.shoeSize.textColor = UIColor.init(hexString: "#737373")
}
}
}
}

UIViewController中,创建一个Shoe类型的数组来保存单元格的数据。您可以在viewDidLoad()方法中分配数据。

var shoes = [Shoe]()

设置UICollectionViewallowsSelectionallowsMultipleSelection属性为true

collectionView.allowsSelection = true
collectionView.allowsMultipleSelection = true

cellForItem方法中传递Shoe数据到单元格。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShoeSizesCell", for: indexPath) as? ShoeSizesCell {
cell.shoe = shoes[indexPath.item]
return cell
}
return UICollectionViewCell()
}

修改didSelectItem方法,如下所示。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
shoes[indexPath.item].isSelected = true
}

和重写didDeselectItemAt方法。

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
shoes[indexPath.item].isSelected = false
}

最新更新