所以,我有一系列的关卡。单元数取决于该阵列。例如,用户已完成3级(或1、3、4、5和93)级别。如何仅更改第3个(或1、3、4、5和93)单元格的背景?
UPD:我尝试仅更改第一个单元格的颜色。颜色已更改,确定。但是当我开始滚动列表时,颜色不仅改变了第一个单元格。
Before Scrolling After Scrolling
import UIKit
class MenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var levelList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return levelList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
cell.levelLabel.text = String(levelList[indexPath.item])
return cell
}
}
答案 0 :(得分:0)
您可以尝试这样的操作,这是假设您有一种方法来获取您似乎已经拥有的完整级别,当然这不是最佳的实现,因为它每次滚动时都会运行for循环通过细胞,这只是让您了解如何操作。
var levelsCompleted = [1,2,3,93]
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
cell.levelLabel.text = String(levelList[indexPath.item])
for i in levelsCompleted {
cell.backgroundColor = levelList.contains(i) ? .red : .white
}
return cell
}