bkwebhero bkwebhero - 3 months ago 23
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.

Code:

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

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

parseObjects[indexPath.row].getDataInBackgroundWithBlock{

(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 {

addToList.append(objectsArray[indexPath.row])

return true

}

Answer

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!) {
        addToList.append(objectsArray[indexPath.row])
        var cell = collectionView.cellForItemAtIndexPath(indexPath)            
        cell.layer.borderWidth = 2.0
        cell.layer.borderColor = UIColor.grayColor().CGColor
  }
Comments