Search code examples
iosswiftgradientcagradientlayer

Subviews are not displaying for CAGradientLayer added view


used below code for adding gradient layer for a view. After adding gradient layer to a view if i tried to add new subviews inside my gradient view the new view are not getting displayed

func setGradientBackground(_ view: UIView ,colorStart:CGColor ,colorEnd:CGColor,cornerRadius:CGFloat) {
let gradientLayer = CAGradientLayer()

gradientLayer.colors = [colorStart, colorEnd]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5);
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5);

gradientLayer.frame = view.bounds
gradientLayer.cornerRadius = cornerRadius

view.layer.addSublayer(gradientLayer)
}  

if i extend a class with UIView how can i set gradient color directly from storyboard attributes inspector. I have seen this in some libraries (cosmos) where we can directly set rating color


Solution

  • Instead of adding gradient layer, create subclass of uiview and override layer property with gradientLayer

    Gradient View:

    @IBDesignable class VerticalGradientView: UIView {
        @IBInspectable var topColor: UIColor = UIColor.red {
            didSet {
                setGradient()
            }
        }
        @IBInspectable var bottomColor: UIColor = UIColor.blue {
            didSet {
                setGradient()
            }
        }
    
        override class var layerClass: AnyClass {
            return CAGradientLayer.self
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            setGradient()
        }
    
        private func setGradient() {
            (layer as! CAGradientLayer).colors = [topColor.cgColor, bottomColor.cgColor]
            (layer as! CAGradientLayer).startPoint = CGPoint(x: 0.5, y: 0)
            (layer as! CAGradientLayer).endPoint = CGPoint(x: 0.5, y: 1)
        }
    }
    

    Use:

    let gradientView = VerticalGradientView()
    gradientView.frame = CGRect(0,0,100,100)
    gradientView.topColor = .black
    
    let label = UILabel()
    gradientView.addSubview(label)