For an iOS app in Swift, I am using programmatic constraints and would like to add a CAGradientLayer() to a UIView(). Below is my code which doesn't work.
import UIKit
class ViewController: UIViewController {
let animationView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(animationView)
setupAnimationView()
animationView.addGradientLayer()
}
func setupAnimationView() {
animationView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
animationView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
animationView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
animationView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
extension UIView {
func addGradientLayer() {
let color1 = UIColor(red: 251/255, green: 55/255, blue: 91/255, alpha: 1.0)
let color2 = UIColor(red: 1.0, green: 70/255, blue: 0, alpha: 1.0)
let gradientLayer = CAGradientLayer()
gradientLayer.name = "gradientLayer"
gradientLayer.frame = self.frame
gradientLayer.colors = [color1.cgColor, color2.cgColor]
self.layer.insertSublayer(gradientLayer, at: 0)
}
}
The issue I am having I believe is related to the fact that I create animationView with programmatic constraints and I then try and add the gradient layer by setting its frame equal to the view of the frame. This code works when I don't use programmatic constraints. Any ideas what I am missing / doing wrong?