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
方法中尝试了它,但它没有用。请帮忙。
答案 0 :(得分:3)
您可以使用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
}
。
backgroundColor
现在使用此功能,无需更改didSelectItemAt indexPath
中backgroundColor
的单元格,它将自动生效并更改所选单元格的{{1}}。
答案 1 :(得分:0)
在cellForItemAt
或didSelectItemAt
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)
cell.contentView.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
collectionView.reloadItemsAtIndexPaths(indexPath)
}
}