Ios – How to highlight selected UICollectionView cells? (Swift)

iosswiftuicollectionview

I have a UICollectionView, and the user is able to select multiple cells. It's a bit difficult to keep track of which cells have been selected, so I need some way to go about highlighting/creating a border when the cell is tapped.

Code:

func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {

    addToList.append(objectsArray[indexPath.row])

    return true

}

Best Solution

you can use border change on didSelectItemAtIndexPath override event like the below code and assign new settings on the cell.

Swift 3.x:

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