bkwebhero bkwebhero - 11 months ago 107
Swift Question

How can I highlight selected UICollectionView cells? (Swift)

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.


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell: CardsCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CardsCollectionViewCell


(imageData: NSData?, error: NSError?) -> Void in

if error == nil {

let image = UIImage(data: imageData!)

cell.cardsImg.image = image


//cell.cardLabel.text = imageNames[indexPath.row]
return cell

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


return true


Answer Source

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

  override func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) {
        var cell = collectionView.cellForItemAtIndexPath(indexPath)            
        cell.layer.borderWidth = 2.0
        cell.layer.borderColor = UIColor.grayColor().CGColor