I want to add the gradient as a background to label. I used the following code to acheive that. but the problem is that though the gradient color appears on the label, but t
You can add UILabel within UILabel
Like this.
class GradientLabel: UILabel {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.clipsToBounds = true
DispatchQueue.main.async {
self.applyGradient(with: Color.gradientColor, gradient: GradientOrientation.topLeftBottomRight)
self.textColor = UIColor.white
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
label.text = self.text
label.font = self.font
label.textColor = self.textColor
label.textAlignment = self.textAlignment
self.text = ""
self.addSubview(label)
}
}
}
extension UIView {
func applyGradient(with colours: [UIColor], locations: [NSNumber]? = nil) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colours.map { $0.cgColor }
gradient.locations = locations
self.layer.insertSublayer(gradient, at: 0)
}
func applyGradient(with colours: [UIColor], gradient orientation: GradientOrientation) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colours.map { $0.cgColor }
gradient.startPoint = orientation.startPoint
gradient.endPoint = orientation.endPoint
self.layer.insertSublayer(gradient, at: 0)
}
}