iOS CollectionView 帮助(保存当前状态)

iOS CollectionView Help (saving current state)

我正在 Swift 制作一个 iOS 应用程序,我 运行 遇到了一个障碍,我似乎被困住了。我有一个由字符串数组填充的集合视图,这是我在集合视图单元格中填充图像的图像的名称:

var tableData: [String] = ["cricket1.png", "cricket1.png", "cricket1.png"]

我已使用以下代码将图像链接到集合视图:

//How many cells there are is equal to the amount of items in tableData (.count property)
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return tableData.count
}

//Linking up collectionView with tableData
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: CricketCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CricketCell
    cell.imgCell.image = UIImage(named: tableData[indexPath.row])
    return cell
}

当我让用户点击单元格时,图像从 cricket1.png 变为 cricket2.png:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        println("Cell selected")

        var cell = collectionView.cellForItemAtIndexPath(indexPath) as! CricketCell


            if cell.imgCell.image == UIImage(named:"cricket1.png"){
                var cell = collectionView.cellForItemAtIndexPath(indexPath) as! CricketCell
                cell.imgCell.image =  UIImage(named:"cricket2.png")

            }

现在..这是我遇到麻烦的地方。我目前正在尝试将数据保存在 tableData 中,但是当我这样做时,它总是将其保存为 ["cricket1.png", "cricket1.png", "cricket1.png"]。即使图像已被点击并更改为 "cricket2.png"。即使屏幕上的所有图像都是 cricket2.png,当我保存 tableData 时,它也会将其保存为 ["cricket1.png", "cricket1.png", "cricket1.png"]。我知道这是因为我正在存储我之前声明的变量 tableData,但是有什么方法可以获取集合视图 screen/the 当前状态的字符串数组?

如有任何帮助,我们将不胜感激!

谢谢!

我建议您使用另一个 属性 来保存单元格的状态。例如,

var selectedState = [true, false, true, true, true]

点击图像后,相应地更新图像和 selectedState 数组。 例如,

if selectedState[indexPath.row] { cell.imgCell.image == UIImage(named:"cricket1.png") else { cell.imgCell.image = UIImage(named:"cricket2.png") }

准备好获取点击的单元格的状态后,您可以使用 selectedState 数组变量。

您不能使用单元格来保持任何状态,因为单元格可能会被 collectionView 取消排队,并且可能会在您滚动时丢失其状态。

希望这对您有所帮助。

您需要自行更新数组中的数据。它独立于图像。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    println("Cell selected")

    //1: Get the index for which data in array you need to update
    let index = indexPath.row

    //I don't think this comparison may server your purpose. When you new an UIImage object, it's a different one than the original image.  You may want to just compare the data
    let unSelectedImage = "cricket1.png"
    if self.tableData[index] != unselectedImage {
         //2: Update data in array
         var cell = collectionView.cellForItemAtIndexPath(indexPath) as! CricketCell
         let selectedImageName = "cricket2.png"
         self.tableData[index] = selectedImageName
         cell.imgCell.image = UIImage(named: selectedImageName)
    } 

}

所以在这种情况下,即使您刷新 table,图像也会根据新的 table 数据加载。