Search code examples
iosswiftuiviewsubviewcagradientlayer

How to set a gradient using CAGradientLayer to a UIView (subview) in swift programatically?


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(container)
        container.customAcnhor(top: view.topAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 350)
        
    }

    let container : UIView = {
        var view = UIView()
        let gradient = CAGradientLayer()
        gradient.frame = view.bounds
        gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
        view.layer.insertSublayer(gradient, at: 0)
        
        return view
    }()
}

Code Context

The above class has a container which it is of type UIView where it contains a CAGradientLayer. I am trying to display the gradient to a subview where I am adding this container(subview) to the main view.
Below is a similar example on how I want to achieve this. The blue colour on the image needs to have my custom gradient.
can some one please help me to solve this problem?

I want the gradient to be on the blue part of the sub-view as something similar shown in the image.


Solution

  • You might have to set the frame of gradient layer once again after laying out the container view.

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            view.addSubview(container)
            container.customAcnhor(top: view.topAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 350)
            gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
        }
        let gradient = CAGradientLayer()
    
        lazy var container : UIView = {
            var view = UIView()
            view.layer.insertSublayer(gradient, at: 0)
            return view
        }()
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            gradient.frame = container.bounds
        }
    }