【发布时间】:2018-08-26 00:58:28
【问题描述】:
我制作了一个集合视图,以便用户可以选择多个选项,并且每次选择单元格都会改变其背景,问题是例如当我选择第一个单元格然后向下滚动绘制的单元格发生变化,而其他单元格被绘制时相反,每次滚动时都会发生变化,这是我用于创建集合视图和绘制单元格的代码
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:ServiciosCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellServicios", for: indexPath) as! ServiciosCollectionViewCell
var borderColor: CGColor! = UIColor.clear.cgColor
var borderWidth: CGFloat = 0
borderColor = UIColor.black.cgColor
borderWidth = 1
cell.imageView.layer.borderWidth = borderWidth
cell.imageView.layer.borderColor = borderColor
let servicio = ServiciosArray[indexPath.row] as! NSDictionary
cell.serviciosLabel.text = servicio["nombre"] as? String
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at:indexPath)
let servicio = ServiciosArray[indexPath.row] as! NSDictionary
if let result_number = servicio["id_servicio"] as? NSNumber
{
if ServiciosSeleccionadosArray.contains(result_number){
ServiciosSeleccionadosArray.remove(result_number)
cell?.contentView.backgroundColor = UIColor.clear
}else{
ServiciosSeleccionadosArray.add(result_number)
cell?.contentView.backgroundColor = UIColor(red:0.72, green:0.33, blue:0.56, alpha:1.0)
}
}}
我根据数组“ServiciosSeleccionadosArray”控制要绘制的单元格(该数组的值不会改变,只有绘制)。
【问题讨论】:
-
这是单元格重复使用的结果。您将需要重组您的代码,以便在
cellForItemAt中您知道当前是否选择了该单元格索引并在那里设置样式。 -
@KevinDiTraglia 你能给我一些关于如何做到这一点的提示吗?还是我必须在 cellForItemAt 的 didselect 中做同样的事情?
标签: ios swift xcode uicollectionview