2016-08-24 94 views
0

我一直在嘗試更改UICollectionView中自定義單元格內的UILabel的文本顏色。目前我使用下面的代碼,讓我改變Cell的背景顏色,但我只需要改變文字顏色:更改自定義UICollectionViewCell中UILabel的文本顏色

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

    } 

我已經看到一些應用程序,其中一個發線樣的東西保持選定下移動細胞。任何人都知道如何實施?

TIA

回答

2

如果它是一個自定義單元格,您將需要一個標籤添加到您的自定義UICollectionViewCell

import UIKit 

class CustomCell: UICollectionViewCell { 

    let label: UILabel! = nil 

} 

然後,在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) 

} 
+0

非常感謝。這正是我需要的:) – Molly

+0

不客氣。如果這有幫助,請選擇它作爲答案和upvote。 – Nate4436271

0
theLableYouWantToChangeColor.textColor = UIColor.redColor() 

正如你所說的自定義UICollectionViewCell,你必須創建一個自定義UICollectionViewCell,並添加UILabel內。

+0

究竟這是我做了什麼: 類SliderCustomCollectionViewCell:UICollectionViewCell { @IBOutlet VAR sliderCellLabel:的UILabel! } – Molly

+0

現在如何讓它在另一個類的函數中可見。具體在didSelect和deSelect方法?最後改變文字的顏色......? – Molly

+0

在cellforItems ....上創建單元格時使用它。我不明白你在做什麼「現在如何讓它在另一個類函數中可見」 – Sofeda

0

你應該有單元格引用,使該標籤屬性訪問從其他類訪問並更改,或者將顏色對象傳遞給單元格並僅在那裏更改它。 其他檢查:引用不應爲零,如果IBOutlet則應該連接。