ios - 如何保存单元格的状态,以便当我滚动或离开页面时不会刷新单元格?

标签 ios swift xcode uicollectionview uicollectionviewcell

我正在尝试为一款游戏创建一个商店,您可以在其中购买不同颜色的球。我首先使用带有所有白球的 UICollectionView,当我单击一个单元格时,它将白球图像更改为彩球图像(编辑:来自预先制作的彩色图像数组的图像)。当我向下滚动并向上滚动时,我选择的单元格将重置为白球图像。我显然不想这样。

我尝试使用已经内置到 UICollectionView 类中的方法和 didSelectItemAt 但是当我向下滚动并向上滚动时,它会变得一团糟(当我选择一个单元格时,不同的图像被更改而不是正确的图像)。我尝试在 collectionViewCell 类中使用 isSelected,但我无法在此处获取索引路径,因此无法保存选择的单元格。

override var isSelected: Bool{
    didSet{
        if self.isSelected
        {
            textImage.image = images[indexPath.item]    // I don't know what to put here I don't have the indexPath

        }
        else
        {
            textImage.image = #imageLiteral(resourceName: "circleWhite")

        }
    }
}

任何帮助都很棒,我对 Xcode 编码还很陌生,所以非常感谢在这里做什么的一些解释。

编辑:我有一组图像应该是商店,而不仅仅是一种不同的颜色,多种颜色。当我单击某个单元格时,它应该访问数组中相应索引中的图像,并使用该图像替换白色圆圈。

最佳答案

在我们的代码中做了同样的事情。下面是解决方案。

1.采用元组数组来维护选定的状态和特定颜色或您想要的任何内容。

var arrColor = [(isSelected:Bool,color:UIColor)]()

2.现在在 cellForItemAt 上执行以下代码。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let collectionViewCell = self.iconCollectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? EditDeviceCollectionViewCell else { return UICollectionViewCell() }

    if arrColor[indexPath.item].isSelected{
        arrColor[indexPath.item].color = .white
    }else {
        arrColor[indexPath.item].color = .black
    }

    return  collectionViewCell
}

3.现在编写数据源方法并使用下面的颜色

//MARK:- UICollectionViewDelegate

扩展yourViewController:UICollectionViewDelegate {

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

}

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

}

祝你编码愉快😊

关于ios - 如何保存单元格的状态,以便当我滚动或离开页面时不会刷新单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55818068/

相关文章:

iOS 核心数据加密

swift - 传递带有子参数类型的闭包

c++ - "Proper way"将文件夹添加到 XCode 4 中的包含路径

ios - 线程 1 : EXC_BREAKPOINT (code=1, subcode=...) 使用 MKMap View 时

ios - 如何检测用户是否在应用程序运行时更改了 iPhone 系统语言设置?

ios - (iOS8) 设置状态栏为亮内容

swift - 在 Swift 中子类化 SCNScene - 覆盖 init

ios - 在 Google Maps iOS API 中创建虚线折线时未解析的标识符

ios - 等到 In App Purchase 完成,直到执行操作

ios - 无法在重构的 Storyboard上设置标签栏角标(Badge)值