I am trying to give my text fields a gradient background. I am using the following code:
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))
}
}
What I did was to create an extension and a class which I will attach to some UITextFields. The result is the gradient layer is a little bit shorter than the textfield and it kind of starts a few pixels higher inside the texfield instead of covering it all. What can I do?
Move code to layoutSubviews
, As it contains the right bounds
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
}
}
}