Ios 我试图添加梯度作为视图中的子层,但它并没有将其调整为与视图相同的大小

Ios 我试图添加梯度作为视图中的子层,但它并没有将其调整为与视图相同的大小,ios,swift,xcode,calayer,Ios,Swift,Xcode,Calayer,我写了上面的代码,根据代码梯度应该覆盖整个视图。但梯度就是这样出现的 这是我用来创建渐变的函数,您可能会发现它很有用 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.0

我写了上面的代码,根据代码梯度应该覆盖整个视图。但梯度就是这样出现的


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

    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)

我想出来了,只是回答我自己,这样以后可能会帮助别人


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

呃,这与OP的代码几乎完全相同,只是有一个动画,你可能必须在ViewDidLayoutSubViews中执行此操作这些神奇的数字来自哪里?你在哪里写这些代码行?
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)
}