我正在尝试将渐变添加为视图中的子层,但它没有调整它的大小等于视图

I am trying to add gradient as a sublayer in view but its not resizing it equal to the view

    let cellview: UIView!
    let gradient = CAGradientLayer() 
    let topColor = UIColor(red: 0.435, green: 0, blue: 0.635, alpha: 1.0)
    let bottomColor = UIColor(red: 0.255 , green: 0.043, blue: 0.373, alpha: 1.0)
    gradient.colors = [topColor.cgColor, bottomColor.cgColor]
    gradient.startPoint = CGPoint(x:0, y:0)
    gradient.endPoint = CGPoint(x:0.3, y:1)
    cellview = UIView(frame: CGRect(x: 0, y: 0, width: 192, height: 160))
    gradient.frame = cellview.bounds
    gradient.masksToBounds = true
    cellview.layer.addSublayer(gradient)

我根据代码渐变应该覆盖整个视图来编写上面的代码。但是渐变是这样出现的

Following is the screen shot for app

这是我用来创建渐变的函数,您可能会发现它很有用

func createGradientBackground(gradientColor: UIColor, darkStylePreferred: Bool, viewToUse: UIView) {
    
    let gradient = CAGradientLayer(layer: viewToUse.layer)
    gradient.frame = viewToUse.bounds
    gradient.locations = [0, 1]
    
    viewToUse.layer.insertSublayer(gradient, at: 0)
    
    let animation = CABasicAnimation(keyPath: "locations")
    
    animation.toValue = [0, 0.11, 1]
    animation.fromValue = [0, 0.9, 1]
    
    if darkStylePreferred {
        gradient.colors = [UIColor.black.cgColor, gradientColor.cgColor, UIColor.black.cgColor]
    } else {
        gradient.colors = [UIColor.white.cgColor, gradientColor.cgColor, UIColor.white.cgColor]
    }
    
    animation.autoreverses = true
    animation.repeatCount = Float.infinity
    animation.speed = 0.015
    animation.isRemovedOnCompletion = false
    gradient.add(animation, forKey: nil)
}

我想出来了,只是回答我自己,所以它可能会帮助以后的人。

我所要做的就是在 func viewDidLayoutSubviews() 中设置渐变。这解决了我的问题