2017-05-06 77 views
0

我有一個應用程序,其中包含一個視圖控制器中的文本字段和另一個視圖控制器中的集合視圖。我正在顯示在集合視圖單元格中鍵入的文本。這工作很好,但是我硬編碼了兩個單元格,我想在用戶輸入的文本上面顯示。我想改變這兩個單元格的背景,這可能嗎? 「名稱」和「成績」是硬編碼的項目由於任何幫助如何更改UICollectionview單元格上的背景swift

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

    return ScoreArray.count  
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 

    let Mycell = Cell.viewWithTag(1) as! UILabel 

    Mycell.text = ScoreArray[indexPath.row] 

    return Cell 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    ScoreArray.append("NAMES") 
    ScoreArray.append("SCORES") 
} 

回答

0

在的tableView的情況下,我們得到默認添加一個內容查看(我想改變的背景的人)。對於的CollectionView我們也使用代碼,例如訪問:

let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyCell 
myCell.contentView.backgroundColor = .gray // contentView is get only 
myCell.contentView.addSubView(UIView()) 
+1

是什麼增加的UIView()爲子視圖嗎?這似乎令人費解。 –

+0

你的問題對我來說很困惑什麼是改變背景的意思..改變顏色,查看或顯示任何東西? – amber

0

要更改背景顏色你的細胞,比如說,綠色環保:

Cell.backgroundColor = UIColor.green 

要改變一個特定的細胞,你需要看看indexPath,因爲indexPath是唯一標識單元格的東西。

indexPath具有段和行屬性。假設你只有一個部分,你可以看看排財產cellForItemAt,像這樣:

if indexPath.row == 0 { 
    // make the first cell green 
    Cell.backgroundColor = UIColor.green 
} 
else { 
    // make all others red 
    Cell.backgroundColor = UIColor.red 
} 
+0

但我如何選擇特定的單元格來改變顏色? – c3pNoah

相關問題