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

时间:2019-12-11 08:33:49

标签: ios swift uicollectionview uicolor

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

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

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

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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

     }

答案 2 :(得分:0)

最后我找到了解决方法。

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

  • 设置单元格背景颜色
  • 添加一个图层,该图层由单元格框架插入
  • 设置图层背景颜色
  • 添加视图
相关问题