这是我第一次使用 CollectionView 。我有一个简单的按钮,它重复了 9 次,因为我用字符串数组填充它。我想更改第一个元素的背景颜色,我可以这样做,但是在 Scroll 上我也得到具有相同背景颜色的其他元素,我只希望第一个元素具有该背景颜色。这是我的代码
class HomeC: UIViewController,CollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet weak var CategoriesView: UICollectionView!
var CategoryIndex = 0
var categoryTypes = ["All","General","Sports","Local Issues","Questions","Politics","Events","Advertise","Sell","Services"]
override func viewDidLoad() {
super.viewDidLoad()
CategoriesView.delegate = self
CategoriesView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categoryTypes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoriesCVC", for: indexPath) as! CategoriesCVC
cell.items.tag = indexPath.row
cell.items.setTitle(categoryTypes[indexPath.row], for: .normal)
if categoryTypes[indexPath.row] == "All" && indexPath.row == CategoryIndex {
cell.items.backgroundColor = UIColor(hexString: BlueBackground)
cell.items.setTitleColor(.white, for: .normal)
}
return cell
}
}
使用该代码,我的第一个元素“全部”具有适当的背景,但是如果我滑过 collectionView,我得到的其他元素也具有蓝色背景。我该如何解决这个问题?任何建议都会很棒。
最佳答案
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoriesCVC", for: indexPath) as! CategoriesCVC
cell.items.tag = indexPath.row
cell.items.setTitle(categoryTypes[indexPath.row], for: .normal)
if categoryTypes[indexPath.row] == "All" && indexPath.row == CategoryIndex {
cell.items.backgroundColor = UIColor(hexString: BlueBackground)
cell.items.setTitleColor(.white, for: .normal)
} else {
// set your normal cell color here
cell.items.backgroundColor = UIColor(hexString: NormalCellColor)
cell.items.setTitleColor(.normalTitleColoe, for: .normal)
}
return cell
}
由于 Collection View 使用出队单元格,因此它采用旧单元格背景。那是蓝色。如果您恢复 else block 中的单元格颜色,那将解决您的问题
如果您想以更专业的方式做事。在单元格 prepareForReuse
上,进行清理。
override open func prepareForReuse() {
super.prepareForReuse()
// Set your default background color, title color etc
}
关于IOS Swift CollectionView 如何在索引上设置正确的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54414600/