我有一个自定义UICollectionViewCell
,它可以选择和取消选择单个单元格。当您选择然后取消选择单元格,滚动到UICollectionView
时,问题就会出现,当您返回之前选择的单元格时,表明它已被选中。这是一些可重用性问题。
这是我选择和取消选择单元格的方式:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)! as! CreateNotebookCVCell
if selectedIndexPath != indexPath || selectedIndexPath == nil {
// Select Cell
selectedIndexPath = indexPath
cell.showDimViewAndCheckmark()
selectedCover = notebookCovers[indexPath.row]
saveButton.isEnabled = true
}
else {
// Deselect Cell
selectedIndexPath = nil
cell.hideDimViewAndCheckmark()
selectedCover = nil
saveButton.isEnabled = false
}
}
这是单元格中的代码:
override func awakeFromNib(){ super.awakeFromNib() setUI() // hideDimViewAndCheckmark() }
override func prepareForReuse() {
super.prepareForReuse()
hideDimViewAndCheckmark()
coverImageView.image = nil
}
func hideDimViewAndCheckmark() {
dimView.isHidden = true
checkmarkIcon.isHidden = true
}
func showDimViewAndCheckmark() {
dimView.isHidden = false
checkmarkIcon.isHidden = false
dimView.layer.cornerRadius = 10
dimView.clipsToBounds = true
dimView.layer.borderWidth = 2
dimView.layer.borderColor = Colors.purpleDarker.cgColor
dimView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
}
override var isSelected: Bool {
didSet {
if isSelected {
UIView.animate(withDuration: 0.1, animations: { [unowned self] in
self.showDimViewAndCheckmark()
})
}
else {
UIView.animate(withDuration: 0.1, animations: { [unowned self] in
self.hideDimViewAndCheckmark()
})
}
}
}
不确定在这里我在做什么错
更新:cellForRowAt
根据要求的方法
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell_Id.createNotebook, for: indexPath) as! CreateNotebookCVCell
let cover = notebookCovers[indexPath.row]
cell.coverImageView.image = UIImage(named: cover)
return cell
}
答案 0 :(得分:1)
尝试一下
-cellForItem函数
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CreateNotebookCVCell
if selectedIndexPath == indexPath{
cell.showDimViewAndCheckmark()
selectedCover = notebookCovers[indexPath.row]
saveButton.isEnabled = true
} else {
cell.hideDimViewAndCheckmark()
selectedCover = nil
saveButton.isEnabled = false
}
return cell
}
-didSelectItemAt函数
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if selectedIndexPath != indexPath || selectedIndexPath == nil {
// Select Cell
selectedIndexPath = indexPath
} else {
// Deselect Cell
selectedIndexPath = nil
}
collectionView.reloadData()
}