如何在UICollectionView上设置渐变固定背景?

我使用了以下代码。

CAGradientLayer* collectionRadient = [CAGradientLayer layer]; collectionRadient.bounds = self.collectionView.bounds; collectionRadient.anchorPoint = CGPointZero; collectionRadient.colors = [NSArray arrayWithObjects:(id)[startColor CGColor],(id)[endColor CGColor], nil]; [self.collectionView.layer insertSublayer:collectionRadient atIndex:0]; 

但它吸收了细胞包括图像。 所以没有显示细胞。

我想在Cells下绘制UICollectionView的渐变背景,并在滚动视图时修复它。 请告诉我。

试试这个……你必须指定一个视图来使用背景视图。

 CAGradientLayer* collectionGradient = [CAGradientLayer layer]; collectionGradient.bounds = self.view.bounds; collectionGradient.anchorPoint = CGPointZero; collectionGradient.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor],(id)[[UIColor greenColor] CGColor], nil]; UIView *vv = [[UIView alloc] init]; vview.backgroundView = vv; [vview.backgroundView.layer insertSublayer:collectionGradient atIndex:0]; 

在Swift 3.0中

我喜欢从渐变的自定义类开始

导入UIKit
 @IBDesignable
 class GradientView:UIView {
     //设置你的起始颜色
     @IBInspectable var startColor:UIColor = UIColor.black {didSet {updateColors()}}
     //设置你的结束颜色
     @IBInspectable var endColor:UIColor = UIColor.white {didSet {updateColors()}}
     //你可以改变锚点和方向
     @IBInspectable var startLocation:Double = 0.05 {didSet {updateLocations()}}
     @IBInspectable var endLocation:Double = 0.95 {didSet {updateLocations()}}
     @IBInspectable var horizo​​ntalMode:Bool = false {didSet {updatePoints()}}
     @IBInspectable var diagonalMode:Bool = false {didSet {updatePoints()}}
     override class var layerClass:AnyClass {return CAGradientLayer.self}
     var gradientLayer:CAGradientLayer {return layer as!  CAGradientLayer}
     func updatePoints(){
         if horizo​​ntalMode {
             gradientLayer.startPoint = diagonalMode?  CGPoint(x:1,y:0):CGPoint(x:0,y:0.5)
             gradientLayer.endPoint = diagonalMode?  CGPoint(x:0,y:1):CGPoint(x:1,y:0.5)
         } else {
             gradientLayer.startPoint = diagonalMode?  CGPoint(x:0,y:0):CGPoint(x:0.5,y:0)
             gradientLayer.endPoint = diagonalMode?  CGPoint(x:1,y:1):CGPoint(x:0.5,y:1)
         }
     }
     func updateLocations(){
         gradientLayer.locations = [startLocation as NSNumber,endLocation as NSNumber]
     }
     func updateColors(){
         gradientLayer.colors = [startColor.cgColor,endColor.cgColor]
     }

     override func layoutSubviews(){
         super.layoutSubviews()
         updatePoints()
         updateLocations()
         updateColors()
     }
 }

使用项目中某处的自定义类并将其添加到目标中,您只需要像前面提到的那样将其添加为背景视图而不是背景颜色或单独的普通视图发送到后面

这样实现:

 let gradient = GradientView()
 gradient.frame = self.view.bounds
 //添加到您的collectionView
的CollectionView?.addSubview(梯度)
 collectionView?.sendSubview(toBack:gradient)
 self.collectionView?.backgroundView = gradient