3

I added a gradient layer to UICollectionView, but the layer is set to the width of the screen. I am trying to keep the layer static while scrolling but can't find a solution. Tried setting to both the frame of the collectionView and to the currentVC, when I scroll the layer is also scrolling. This is my code so far, thank you for your help.

let gradinatLayer = CAGradientLayer()
    gradinatLayer.frame = self.collectionView.frame //self.currentViewController.view.frame

    let cgColors:[CGColorRef] = [UIColor.blackColor().colorWithAlphaComponent(0.7).CGColor, UIColor.clearColor().CGColor, UIColor.blackColor().colorWithAlphaComponent(0.7).CGColor]

    gradinatLayer.colors = cgColors
    gradinatLayer.startPoint = CGPointMake(0, 0.5)
    gradinatLayer.endPoint = CGPointMake(1.0, 0.5)
    gradinatLayer.locations = [0.15, 0.50, 0.85]

    self.collectionView.layer.insertSublayer(gradinatLayer, atIndex: 0)

//This doesn't work
self.collectionView.layer.shouldRasterize = true
self.collectionView.layer.rasterizationScale = UIScreen.mainScreen().scale
Tal Zion
  • 6,308
  • 3
  • 50
  • 73

2 Answers2

2

Thank you for all your comments. This was my solution after digging into UIView. Unfortunately, adding super views and subviews to UICollectionView still keeps the view scrollable. Thanks to John Stephen, who showed how to create a transparent UIView with userIntaractions with its child views, this was possible.

I have declared a @IBOutlet weak var passThroughView: PassThroughView! on top of collectionView.

This is the code that works now:

let gradinatLayer = CAGradientLayer()
    gradinatLayer.frame = self.currentViewController.view.frame

    let cgColors:[CGColorRef] = [UIColor.blackColor().colorWithAlphaComponent(0.7).CGColor, UIColor.clearColor().CGColor, UIColor.blackColor().colorWithAlphaComponent(0.7).CGColor]

    gradinatLayer.colors = cgColors
    gradinatLayer.startPoint = CGPointMake(0, 0.5)
    gradinatLayer.endPoint = CGPointMake(1.0, 0.5)
    gradinatLayer.locations = [0.15, 0.50, 0.85]

    passThroughView.layer.insertSublayer(gradinatLayer, atIndex: 0)
Community
  • 1
  • 1
Tal Zion
  • 6,308
  • 3
  • 50
  • 73
0

Try adding your layer to the collectionView's backgroundview instead:

self.collectionView.backgroundView.layer.addSublayer(gradinatLayer)

JDA3
  • 356
  • 3
  • 7
  • Hi @JDA3, thank you for your answer but this will not work as this is a backgroundView, which means it is behind the cells and won't be visible on top of the cells, hence, we need to add a top layer to the collectionView. – Tal Zion May 01 '16 at 18:29
  • If you want the gradient above the cells, then you will want to add a new view to the collectionView's .superView, make it transparent, and add the gradient to it. – JDA3 May 02 '16 at 02:47