Adding a CGGradient as sublayer to UILabel hides the text of label

前端 未结 5 1127
青春惊慌失措
青春惊慌失措 2020-12-03 17:17

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

5条回答
  •  醉话见心
    2020-12-03 17:30

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

提交回复
热议问题