如何在单元格部分而不是 header 部分设置背景颜色?

How to set background color in cell section not header section?

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

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

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

您可以在您的 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
}

您可以使用以下代码完成:

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

     }

终于找到解决方法了

cell中有两个UIView,分别是cell View和contentView。您添加的所有视图都在 contentView 中。所以我应该:

  • 设置单元格背景颜色
  • 添加一个由单元格框架插入框架的图层
  • 设置图层背景颜色
  • 添加观看次数