Search code examples
iosswiftuicollectionviewuilabeluicollectionviewcell

Change text color of UILabel inside Custom UICollectionViewCell


I have been trying to change the Text Color of a UILabel inside a Custom cell in UICollectionView. Currently I am using following code which allows me to change background color of the Cell but I only need to change the text color:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {

    //Change background color of selected Cell

    let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!

    selectedCell.contentView.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)

    }


func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath)
    {

    //Set background color of selected Cell to Clear Color 

    let cellToDeselect:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!

    cellToDeselect.contentView.backgroundColor = UIColor.clearColor()

    }

I have seen few apps in which a hair line kind of thing keeps moving under selected cell. Anyone knows how to implement that as well?

TIA


Solution

  • If its a custom Cell you will need to add a label to your custom UICollectionViewCell

    import UIKit
    
    class CustomCell: UICollectionViewCell {
    
        let label: UILabel! = nil
    
    }
    

    Then, in selectItemAtIndexPath:

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        let selectedCell: CustomCell = collectionView.cellForItemAtIndexPath(indexPath) as! CustomCell
        selectedCell.label.textColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
    
    }