Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 为什么我的渐变层覆盖了我的collectionView单元格?_Swift_Uicollectionview_Uicollectionviewcell_Cagradientlayer - Fatal编程技术网

Swift 为什么我的渐变层覆盖了我的collectionView单元格?

Swift 为什么我的渐变层覆盖了我的collectionView单元格?,swift,uicollectionview,uicollectionviewcell,cagradientlayer,Swift,Uicollectionview,Uicollectionviewcell,Cagradientlayer,我有一个添加了gradientLayer的collectionView。当我构建和运行项目时,我得到了覆盖collectionView单元的gradientLayer。有人知道我该怎么解决这个问题吗 gradientLayer = CAGradientLayer() gradientLayer.frame = view.frame gradientLayer.colors = [#colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607

我有一个添加了gradientLayer的collectionView。当我构建和运行项目时,我得到了覆盖collectionView单元的gradientLayer。有人知道我该怎么解决这个问题吗

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)

问题是集合视图的子视图(单元格)也会向其中添加子层。你的渐变层就在上面


一个简单的解决方案是只使用渐变层创建一个单独的视图,并将集合视图放在其中。为集合视图设置清晰的背景将确保渐变层在单元格下方可见。

鉴于您的目标是将渐变作为背景,您应该使用
UICollectionView
来保存它:

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
我写道,没有编译器,因此可能需要进行一些调整


确保您的集合视图单元格具有透明背景。

以下是@theMikeSwan提供的答案的Swift 5编译版本:

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