Search code examples
iosswiftuicollectionviewcalayercagradientlayer

How to set UICollectionView layer not moving/static while scrolling Swift


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

Solution

  • 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)