I have a simple calculator UI in which I'm trying to add a gradient programmatically to the background of the result/output label. Problem is you can only do that using subviews if you still want to show at the front. But when I do this, the UI gets all distorted on screen.
Below are two stackoverflow threads which suggest using subviews for tasks similar to mine:
Adding a CGGradient as sublayer to UILabel hides the text of label
The code I use to add the gradient through subviews is based on the above solutions:
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRectMake(1, 1, resultLabel.frame.width-2, resultLabel.frame.height-2) //resultLabel.bounds
gradientLayer.colors = [UIColor.greenColor().CGColor as CGColorRef, UIColor.blueColor().CGColor as CGColorRef]
gradientLayer.locations = [0.0, 1.0]
var labelBackground = UIView(frame: resultLabel.frame)
resultLabel.backgroundColor = UIColor.clearColor()
resultLabel.frame = resultLabel.bounds
labelBackground.layer.addSublayer(gradientLayer)
labelBackground.addSubview(resultLabel)
self.view.addSubview(labelBackground)
Although it applies the needed gradient, the display is distorted heavily.
I'm using Swift 2.2 with Xcode 7.3.1
What am I doing wrong ?
Before adding gradient through subviews:
After: