I am trying to add a gradient layet to my UILabel for some reasons the CAGradientLayer covers my text.
Am I doing anything wrong
- (voi
If you for example need to subclass your UILabel, then add some CALayer which covers the text, it is recommended to add CATextLayer to your CALayer, here is an swift example:
@IBDesignable class BWRoundedLabel: UILabel {
override var text: String? {
didSet {
updateView()
}
}
@IBInspectable override var shadowColor: UIColor? {
didSet {
updateView()
}
}
private func updateView() {
let width = bounds.size.width - 1
let height = bounds.size.height - 1
let shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: CGRectMake(0, 0, width, height), cornerRadius: width/2).CGPath
shadowLayer.fillColor = UIColor.yellowOrange().CGColor
shadowLayer.shadowColor = shadowColor?.CGColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0, height: 1.0)
shadowLayer.shadowOpacity = 1
shadowLayer.shadowRadius = 0
let textLayer = CATextLayer()
textLayer.foregroundColor = UIColor.whiteColor().CGColor
textLayer.string = text
textLayer.fontSize = font.pointSize
textLayer.font = "Calibri-Bold"
textLayer.alignmentMode = kCAAlignmentCenter
textLayer.frame = CGRectMake(0, (height - 16)/2, width, 16)
if let sublayers = layer.sublayers {
for sublayer in sublayers {
sublayer.removeFromSuperlayer()
}
}
layer.insertSublayer(shadowLayer, atIndex: 0)
layer.insertSublayer(textLayer, atIndex: 1)
}
}