Search code examples
iosswiftuicollectionviewcagradientlayer

Black to Clear Gradient Disappears when view is scrolled


I have a CAGradientLayer with two colors, black and clear. When the view appears, the gradient displays appropriately however as soon as I scroll my CollectionView, the clear section of the gradient disappears.

let gradient: CAGradientLayer = {
    let g = CAGradientLayer()
    g.colors = [UIColor.black.cgColor, UIColor.clear.cgColor]
    g.startPoint = CGPoint(x: 0.5, y: 1)
    g.endPoint = CGPoint(x: 0.5, y: 0)
    return g
}()

Below is the initial behavior. Initial Behavior

Below is the behavior after scrolling. Behavior After Scrolling

Any suggestions?

EDIT I have included some extra code which includes both the setup of the UIView and the addition of the gradient layer.

let toolBar: UIView = {
    let n = UIView()
    n.translatesAutoresizingMaskIntoConstraints = false
    n.backgroundColor = UIColor.clear
    return n
}()

    view.addSubview(s.toolBar)
    view.addConstraintsWithFormat("H:|[v0]|", views: s.toolBar)
    s.toolBar.heightAnchor.constraint(equalToConstant: 50).isActive = true
    s.toolBar.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    s.toolBar.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    s.toolBar.layer.insertSublayer(s.gradient, at: 0)
    s.gradient.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)

Solution

  • The view was being created at override func viewWillLayoutSubviews() instead of override func viewDidLoad() so whenever the view was scrolled another instance of the gradient was created for however many times viewWillLayoutSubviews was called resulting in multiple gradients being overlaid.