Search code examples
iosswiftextension-methodscagradientlayer

Change Gradient Background of UIView Through Sublayer


I've got this function defined in an extension of UIView which I use to set the gradient background on a UIView:

func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.locations = [0, 1]
    gradientLayer.frame = bounds
    gradientLayer.cornerRadius = withCornerRadius
    layer.insertSublayer(gradientLayer, at: 0)
}

It is used as follows:

view.setGradientBackground(colorTop: UIColor.blue, colorBottom: UIColor.red, withCornerRadius: 10)

The problem is, if I have already called this function once on a view, the second time I call it, it does not do anything. I suspect this is caused by the subLayer persisting from the previous insertion.

I've tried adding:

if layer.sublayers?.count ?? 0 > 0 {
    layer.sublayers?.remove(at: 0)
}

to the top of that function, but that causes by code to crash with a BAD_INSTRUCTION exception.


Solution

  • You can get the Gradient layer and can remove from view anywhere you want to ... Not just by adding it again you remove it..

    if let gradientLayer = (yourView.layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {
    
        print("gradientLayer is presnet")
           gradientLayer.removeFromSuperlayer() 
    
    } else {
    
        print("its not added on layer yet")
    }