gpt4 book ai didi

ios - 使用属性观察器更改 Collection View 单元格是否不好?

转载 作者:行者123 更新时间:2023-11-30 12:04:31 24 4
gpt4 key购买 nike

class SceneCell: UICollectionViewCell {

override var isSelected: Bool {
didSet {
setSelected(bool: isSelected)
}
}

override var isHighlighted: Bool {
didSet {
setHighlighted(bool: isHighlighted)
}
}

@IBOutlet weak var thumbnailImageView: UIImageView!

override func draw(_ rect: CGRect) {
super.draw(rect)

self.backgroundColor = .clear
self.thumbnailImageView.layer.borderColor = UIColor.green.cgColor
self.thumbnailImageView.layer.masksToBounds = true
self.thumbnailImageView.clipsToBounds = true
self.thumbnailImageView.layer.cornerRadius = 8
}

func update(with scene: Scene) {

}

private func setHighlighted(bool: Bool) {
if bool {
self.alpha = 0.5
} else {
self.alpha = 1.0
}
}

private func setSelected(bool: Bool) {
if bool {
self.thumbnailImageView.layer.borderWidth = 2.5
} else {
self.thumbnailImageView.layer.borderWidth = 0
}
}
}

在我的代码中,当 isSelected 设置为 true 时,我将 ImageView 的图层边框宽度更改为 2.5。

当我选择一个单元格并滚动 Collection View 时,我认为在重用该选定单元格时单元格保持选定状态,但重用单元格会更改为未选定状态。其次,当我返回到选定的单元格并重新使用未选定的单元格时,我认为它处于未选定状态。但单元格会自动设置为选中状态。

Collection View 会自动管理这些吗?

最佳答案

问题的代码运行良好。这是记录单元格选择并应用选定/取消选定状态设置的替代解决方案。

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
//......

var selectedIndexPaths = [IndexPath]()

public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPaths.append(indexPath)
}

public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let index = selectedIndexPaths.index(of: indexPath) {
selectedIndexPaths.remove(at: index)
}
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//...
cell.setSelected(selectedIndexPaths.contains(indexPath)) //Remember to make the cell's setSelected() public.
//...
}

//......
}

关于ios - 使用属性观察器更改 Collection View 单元格是否不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46823508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com