我有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
的值,调试时我会注意到这一点。为什么?
答案 0 :(得分:2)
在这一行:
var currentModel = model.models[indexPath.row]
如果models
是一个结构数组,则currentModel
是一个副本,因此设置属性currentModel
不会影响该数组中的任何内容。
答案 1 :(得分: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)
}
}
答案 2 :(得分:1)
更改值后,您需要更新数组。由于struct是按值传递而不是引用。
currentModel = model.models[indexPath.row]
currentModel.isEnlarged = true
model.models[indexPath.row] = currentModel
添加前请务必检查索引是否可用。