如何在单元格区域而不是标题区域中设置背景颜色?

问题描述 投票:0回答:3

我创建了一个collectionView,并希望设置单元格部分的背景颜色

因为我不知道它有多少行,并且我不想在其他部分中设置背景颜色

设置整个单元格部分的背景颜色

ios swift uicollectionview uicolor
3个回答
1
投票

您可以在cellForItemAt上完成此操作,希望对您有所帮助:)

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SampleCell
    if indexPath.section == 1 {
        cell.backgroundColor = UIColor.systemPink
    } else {
        cell.backgroundColor = UIColor.white
    }
    return cell
}

0
投票

您可以使用以下代码进行操作:

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TestCell

        if indexPath.section == 1 {

           cell.backgroundColor = UIColor.red

        } else {

           cell.backgroundColor = UIColor.orange

        }

        return cell

     }

0
投票

终于找到了解决方法。

[单元格中有两个UIView,分别是单元格View和contentView。您添加的所有视图都位于contentView中。所以我应该:

  • 设置单元格背景色
  • 添加一个层,该层由单元格帧插入
  • 设置图层背景颜色
  • 添加视图
© www.soinside.com 2019 - 2024. All rights reserved.