如何更改UICollectionview单元格上的背景swift
问题描述:
我有一个应用程序,其中包含一个视图控制器中的文本字段和另一个视图控制器中的集合视图。我正在显示在集合视图单元格中键入的文本。这工作很好,但是我硬编码了两个单元格,我想在用户输入的文本上面显示。我想改变这两个单元格的背景,这可能吗? “名称”和“成绩”是硬编码的项目由于任何帮助如何更改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")
}
答
在的tableView的情况下,我们得到默认添加一个内容查看(我想改变的背景的人)。对于的CollectionView我们也使用代码,例如访问:
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyCell
myCell.contentView.backgroundColor = .gray // contentView is get only
myCell.contentView.addSubView(UIView())
答
要更改背景颜色你的细胞,比如说,绿色环保:
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
是什么增加的UIView()为子视图吗?这似乎令人费解。 –
你的问题对我来说很困惑什么是改变背景的意思..改变颜色,查看或显示任何东西? – amber