Kauna Mohammed
Kauna Mohammed

Reputation: 1137

Why is my gradient layer covering my collectionView cells?

I have a collectionView with a gradientLayer added to it. When I build and run the project I get the gradientLayer covering the cells of the collectionView. Anyone have an idea on how I could fix this?

gradientLayer = CAGradientLayer()
gradientLayer.frame = view.frame
gradientLayer.colors = [#colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1).cgColor ,#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.1, y: 0.5)
homeCollectionView.layer.insertSublayer(gradientLayer, at: 0)

Upvotes: 1

Views: 1466

Answers (3)

WayneYHuang
WayneYHuang

Reputation: 23

Here's the Swift 5 compiled version of the answer provided by @theMikeSwan:

let bgView = UIView(frame: homeCollectionView.bounds)
let gradientLayer = CAGradientLayer()
gradientLayer.frame = view.frame
gradientLayer.colors = [#colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1).cgColor ,#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.1, y: 0.5)

bgView.layer.insertSublayer(gradientLayer, at: 0)
homeCollectionView.backgroundView = bgView

Upvotes: 1

theMikeSwan
theMikeSwan

Reputation: 4729

Given that your objective is to have the gradient as a background you should use UICollectionView's backgroundView to hold it:

let bgView = UIView(frame: homeCollectionView.bounds)

gradientLayer = CAGradientLayer()
gradientLayer.frame = view.frame
gradientLayer.colors = [#colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1).cgColor ,#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.1, y: 0.5)

bgView.layer = gradientLayer
homeCollectionVIew.backgroundView = bgView

I wrote that without a compiler so some tweaking may be required.

Make sure your collection view cells have transparent backgrounds.

Upvotes: 2

algrid
algrid

Reputation: 5954

The problem is that subviews (cells) of your collection view also add sublayers to it. And your gradient layer ends up on top of it.

An easy solution would be to create a separate view with your gradient layer only and put your collection view inside it. Having a clear background for your collection view will ensure that the gradient layer will be visible below your cells.

Upvotes: 1

Related Questions