CollectionViewCells随滚动而变化

时间:2018-03-16 21:09:21

标签: ios swift xcode uicollectionview

我创建了一个集合视图,以便用户可以选择多个选项,并且每个选项都会更改单元格的背景,问题是例如我选择第一个单元格然后向下滚动绘制的单元格会更改,其他人会被绘制相反,每次滚动时这都会不断变化,这是我用来创建集合视图和绘制单元格的代码

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”控制要绘制的单元格(此数组的值不会改变,只有绘画)。

1 个答案:

答案 0 :(得分:1)

可以随意重构以减少代码重复,但最快的解决方法是在cellForItemAt didSelectItemAt中对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 if let result_number = servicio["id_servicio"] as? NSNumber { if ServiciosSeleccionadosArray.contains(result_number){ cell.contentView.backgroundColor = UIColor(red:0.72, green:0.33, blue:0.56, alpha:1.0) } else { cell.contentView.backgroundColor = UIColor.clear } } return cell } 进行类似的检查:

df2 = pd.DataFrame([df.pop(x) for x in ['c', 'd']]).T
df3 = pd.DataFrame([df.pop(x) for x in ['a', 'b']]).T