Hello! I am creating UIView (subview of main view) and I want to add gradient for background, but I don't use CGRect for create UIView only autolayout therefore my UIView has coordinates 0, 0, width 0 and hight 0. So when I try to use addSubLayer nothing happen. What should I do?
//gradient
var gradient: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.colors = [
UIColor(red: 25/255, green: 25/255, blue: 186/255, alpha: 1).cgColor,
UIColor(red: 177/255, green: 146/255, blue: 125/255, alpha: 1).cgColor
]
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 0.5)
return gradient
}()
//UIView
var win: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.addSublayer(gradient)
gradient.frame = view.bounds
return view
}()
//layout
func winConstraint(_ collections: UICollectionView, _ view: UIView, _ btn: UIView) {
btn.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 25).isActive = true
btn.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -25).isActive = true
btn.topAnchor.constraint(equalTo: collections.bottomAnchor, constant: 8).isActive = true
btn.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
//from ViewController
view.addSubview(win)
So i found the solution! If we want to customize our button or view or something else view gradient background
- if we use only layout and don't use CGRect for button or UIView doesn't matter frame of our UIView is gonna be 0, 0, 0, 0
therefore
gradient.frame = (0, 0, 0, 0)
but its only in ViewDidLoad method:) if we will use viewDidLayoutSubviews() method, we will get updated size of our button or view and therefore we have to do
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews...
gradient.frame = view.bounds
}