Molly
Molly

Reputation: 247

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

Upvotes: 1

Views: 2770

Answers (3)

Sanoj Kashyap
Sanoj Kashyap

Reputation: 5060

You should have cell reference and make that label property accessible from other class and access and change that Or pass the color object to cell and change it there only. Other checks: Reference should not be nil, If IBOutlet then it should be connected.

Upvotes: 0

Nate4436271
Nate4436271

Reputation: 870

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)

}

Upvotes: 3

Sofeda
Sofeda

Reputation: 1371

theLableYouWantToChangeColor.textColor = UIColor.redColor()

As you say custom UICollectionViewCell, you have to create a custom UICollectionViewCell and add a UILabel inside.

Upvotes: 0

Related Questions