func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//let imageView = UIImageView()
//cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor
//cell.placeLabel.tintColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor
cell.layer.cornerRadius = 40
cell.layer.masksToBounds = true
print("places\(indexPath.row)")
//cell.placeLabel.text = places[indexPath.row] as! String
cell.placeLabel.text = places[indexPath.row]
cell.placeLabel.textColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
if (indexPath.row == 0){
cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
}
}
我创建了一个自定义 collectionViewCell 。当我单击其中一个单元格时,它的 backgroundColor 应该会改变。我怎样才能做到这一点?
我已经在 didSelectItemItamAt indexpath 方法中尝试过,但它不起作用。请帮忙。
Best Answer-推荐答案 strong>
您可以使用 selectedBackgroundView UICollectionViewCell 的属性,在 cellForItemAt indexPath 内设置该属性,现在当您选择单元格时,它将自动更改该单元格的 backgroundColor 。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//Your other code
//Add code to set selectedBackgroundView property
let view = UIView(frame: cell.bounds)
// Set background color that you want
view.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.selectedBackgroundView = view
return cell
}
现在使用它不需要更改 didSelectItemAt indexPath 中单元格的 backgroundColor 它将自动工作并更改该选定单元格的 backgroundColor .
关于ios - 如何在 swift iOS 中更改自定义 Collection View 单元格的背景颜色?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/41157918/
|