简体   繁体   中英

Swift4, Background Color when cell is selected

I am attempting to highlight the background of a cell when a user selects it. I have been successful in changing the border of a cell when a user selects it.

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    addToList.append(objectsArray[indexPath.row])
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.contentView.layer.borderWidth = 2.0
    cell?.contentView.layer.borderColor = UIColor.gray.cgColor
}

I have not been able to change the background though.

Can this be done? Thanks!

For cell border, use cell contentView like this:

cell?.contentView.layer.borderWidth = 2.0
cell?.contentView.layer.borderColor = UIColor.gray.cgColor

And for cell backgroundColor color you need to use:

cell?.backgroundColor = .gray

Try this.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell.contentView.backgroundColor = UIColor.red
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell.contentView.backgroundColor = UIColor.white
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM