我正在尝试在集合视图中选择我的第一个单元格时,这里出现的是它的代码
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let indexPath = IndexPath(item: 0, section: 0)
categoryCollectionView.selectItem(at: indexPath
, animated: false, scrollPosition: UICollectionView.ScrollPosition(rawValue: 0))
self.collectionView(categoryCollectionView, didSelectItemAt: indexPath)
}
我在我的 collectionViewCell 类中有一个对 isSelected 变量的覆盖以更改文本颜色
override var isSelected: Bool {
didSet {
if self.isSelected {
self.categoryName.textColor = UIColor(red: 237/255, green: 28/255, blue: 36/255, alpha: 1.0)
} else {
self.categoryName.textColor = UIColor(red: 63/255, green: 62/255, blue: 62/255, alpha: 1.0)
}
}
}
但它不起作用
我通过操作 isSelected 属性来解决它,它工作正常
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.categoryCollectionView {
if let cell = categoryCollectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCollectionViewCell", for: indexPath) as? CategoryCollectionViewCell {
cell.configureCell(text: categories[indexPath.row].name)
if indexPath.row == 0 {
cell.isSelected = true
}
return cell
}
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.categoryCollectionView {
if indexPath != IndexPath(row: 0, section: 0) {
collectionView.cellForItem(at: IndexPath(row: 0, section: 0))?.isSelected = false
}
}
}