我有一个collectionView,其中添加了gradientLayer。当我构建并运行项目时,我得到了覆盖了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)
答案 0 :(得分:1)
问题在于,集合视图的子视图(单元格)也会向其添加子层。然后您的渐变层最终会在其顶部。
一个简单的解决方案是仅使用渐变图层创建一个单独的视图,然后将集合视图放入其中。收集视图的背景清晰可确保渐变层在您的单元格下方可见。
答案 1 :(得分:1)
鉴于您的目标是将渐变作为背景,应使用UICollectionView
的{{3}}来保持渐变:
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
我写道,没有编译器,因此可能需要一些调整。
确保您的收藏夹视图单元格具有透明背景。
答案 2 :(得分:0)
这是@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