为什么我的渐变层比我应用它的 UITextField 小?

Why is my Gradient Layer smaller than the UITextField I am applying it to?

我正在尝试为我的文本字段提供渐变背景。我正在使用以下代码:

import UIKit

extension UITextField {
    func gradientBackground(firstColor: UIColor, secondColor: UIColor){
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x:0.0, y:0.0)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
        layer.addSublayer(gradientLayer)
    }
}

class gradientTeLabel: UITextField {
    override func didMoveToWindow() {
        self.gradientBackground(firstColor: UIColor(red: 0.90, green: 0.61, blue: 0.00, alpha: 1), secondColor: UIColor(red: 0.70, green: 0.61, blue: 0.70, alpha: 1))
    }
}

我所做的是创建一个扩展和一个 class,我将附加到一些 UITextFields。结果是渐变层比文本字段短一点,它在文本字段内开始高几个像素而不是覆盖它。我能做什么?

将代码移至 layoutSubviews ,因为它包含右边界

class gradientTeLabel: UITextField {
    var once = true
     override func layoutSubviews() {
      super.layoutSubviews()
        if once {
              self.gradientBackground(firstColor: UIColor(red: 0.90, green: 0.61, blue: 0.00, alpha: 1), secondColor: UIColor(red: 0.70, green: 0.61, blue: 0.70, alpha: 1))
              once = false 
        }
    }
}