Angella Yu
Angella Yu

Reputation: 62

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

I created a collectionView and want to set the cell section background color

since I do not know how many rows it have and I do not want to set background color in other sections

set the whole cell section backgroundcolor

Upvotes: 0

Views: 448

Answers (3)

Angella Yu
Angella Yu

Reputation: 62

finally I find the solution.

In the cell there is two UIView that is cell View and contentView. And all views you add is in the contentView. So I should:

  • set the cell background color
  • add a layer which frame is inseted by the cell frame
  • set the layer background color
  • add views

Upvotes: 0

Aira Samson
Aira Samson

Reputation: 243

You can do it on your cellForItemAt, hope this helps :)

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
}

Upvotes: 1

Kishan Bhatiya
Kishan Bhatiya

Reputation: 2368

You can do it with following code:

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

     }

Upvotes: 0

Related Questions