gpt4 book ai didi

swift - Collection View 行颜色在滚动时发生变化

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

我有这个 Collection View ,并且在根据其索引绘制每一行时设置了其行的颜色。它会显示每行的正确颜色,直到您向下滚动然后再次向上滚动。例如,如果它的顺序是 R、G、B、R、G、B,那么当上下滚动一点时,它可能是 G、G、R、B、R、B。我尝试将光栅化图层设置为 true 和 false,但也没有运气。我不明白为什么会发生这种情况以及如何解决它。因为我在 cellForItemAt 函数上设置了颜色,并且每当再次绘制一行并将行颜色基于该行的颜色和 id 列表时,它应该被调用,它应该总是绘制相同的东西。

这是我的代码的一部分。

class MyCollectionViewController: UICollectionViewController {
//MARK: Properties

var list = [Item]()
var colors = [[String]]()

override func viewDidLoad() {
super.viewDidLoad()
self.refreshList(self)
colors.append(["#ff3e99","#ffa35a"])
colors.append(["#668dff","#ff53ff"])
colors.append(["#6ae0d7","#00d3ad"])
}

override func numberOfSections(in tableView: UICollectionView) -> Int {
return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return list.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "xxxx"

guard let cell = self.collectionView?.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? xxxxCell else {
fatalError("The dequeued cell is not an instance of xxxx.")
}
// Fetches the appropriate meal for the data source layout.
let item = list[indexPath.row]
style(cell: cell.rootView, index: item.id!)

return cell
}

func style(cell:LGButton, index: Int) {
cell.gradientStartColor = UIColor(hexString: colors[index % colors.count][0])
cell.gradientEndColor = UIColor(hexString: colors[index % colors.count][1])
cell.shadowColor = UIColor(hexString: colors[index % colors.count][0])
cell.shadowRadius = 8
cell.shadowOpacity = 0.8
}

}

最佳答案

滚动时出现的问题让我认为这是单元格重用问题。尝试在自定义 xxxxCell UICollectionViewCell 中实现 prepareForReuse。重置属性并查看是否有帮助。

类似于:

override func prepareForReuse() {
super.prepareForReuse()
gradientStartColor = UIColor.clear
gradientEndColor = UIColor.clear
shadowColor = UIColor.clear
}

关于swift - Collection View 行颜色在滚动时发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203267/

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