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

时间:2018-07-11 14:27:45

标签: swift xcode uitextfield cagradientlayer

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

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))
    }
}

Actual View

我所做的是创建一个扩展和一个类,并将其附加到某些UITextFields上。结果是渐变层比文本字段短一点,并且它开始在texfield内部高出几个像素,而不是全部覆盖。我该怎么办?

1 个答案:

答案 0 :(得分:1)

将代码移动到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 
        }
    }
}