0

我有 UICollectionView 具有以下模型:

class MainVCModel {

    let models = [
        CellModel.init(UIImage.init(named: "1.jpg")!),
        CellModel.init(UIImage.init(named: "2.jpg")!),
        CellModel.init(UIImage.init(named: "3.jpg")!),
        CellModel.init(UIImage.init(named: "4.jpg")!),
        CellModel.init(UIImage.init(named: "5.jpg")!),
        CellModel.init(UIImage.init(named: "6.jpg")!),
        CellModel.init(UIImage.init(named: "7.jpg")!),
        CellModel.init(UIImage.init(named: "8.jpg")!),
        CellModel.init(UIImage.init(named: "9.jpg")!),
    ]
}

struct CellModel {
    var isEnlarged: Bool = false
    var image: UIImage

    lazy var rotatedImage: UIImage = self.image.rotate(radians: Float(Helper.degreesToRadians(degrees: 6)))!

    init(_ image: UIImage){
        self.image = image
    }
}

在我的 CollectionViewController 类中,我有:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var currentModel = model.models[indexPath.row]
        if !currentModel.isEnlarged {
            print("should enlarge")
            currentModel.isEnlarged = true
            enlargeOnSelection(indexPath)
        }   else {
            print("should restore")
            currentModel.isEnlarged = false
            restoreOnSelection(indexPath)
        }
    }

但是当我设置 currentModel.isEnlarged = true它没有效果时,它实际上存储了false值,我在调试时注意到了这一点。为什么?

4

3 回答 3

2

在这一行:

var currentModel = model.models[indexPath.row]

Ifmodels是一个结构体的数组,currentModel是一个副本,因此设置 的属性currentModel不会影响数组中的任何内容。

于 2019-04-11T20:07:19.487 回答
1

您必须将代码更新为此,因为您将新值保存在主模型的副本中。

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var currentModel = model.models[indexPath.row]
        if !currentModel.isEnlarged {
            print("should enlarge")
            model.models[indexPath.row].isEnlarged = true
            enlargeOnSelection(indexPath)
        }   else {
            print("should restore")
            model.models[indexPath.row].isEnlarged = false
            restoreOnSelection(indexPath)
        }
    }
于 2019-04-11T20:09:07.107 回答
1

更改值后,您需要更新数组。由于 struct 是按值传递而不是引用。

currentModel = model.models[indexPath.row]
currentModel.isEnlarged = true
model.models[indexPath.row] = currentModel

添加前请注意检查索引是否可用。

于 2019-04-11T20:42:45.550 回答