添加子视图时屏幕失真

时间:2016-07-23 04:55:43

标签: ios swift xcode uiview swift2

我有一个简单的计算器用户界面,我试图以编程方式将渐变添加到结果/输出标签的背景中。问题是,如果您仍想在前面显示,则只能使用子视图执行此操作。但是当我这样做时,UI会在屏幕上变形。

下面是两个stackoverflow线程,建议使用类似于我的任务的子视图:

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

UILabel add GradientLayer

我用来通过子视图添加渐变的代码基于以上解决方案:

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)

虽然它应用了所需的渐变,但显示会严重失真。

我正在使用Swift 2.2和Xcode 7.3.1

我做错了什么?

在通过子视图添加渐变之前:

enter image description here

后:

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个:

let labelBackground: UIView = UIView(frame: self.resultLabel.frame)
self.resultLabel.backgroundColor = UIColor.clearColor()
self.resultLabel.frame = self.resultLabel.bounds

let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.frame = labelBackground.layer.bounds
gradientLayer.colors = [UIColor.greenColor().CGColor as CGColorRef, UIColor.blueColor().CGColor as CGColorRef]
gradientLayer.locations = [0.0, 1.0]

labelBackground.layer.addSublayer(gradLayer)
labelBackground.addSubview(self.resultLabel)

self.view.addSubview(labelBackground)

答案 1 :(得分:0)

所以我设法使用不同的技术自己解决了这个问题。

我想要一个带有渐变填充的UILabel,同时将文本保留在前面的UILabel中。

为了达到这个目的,我在UILabel后面放了一个UIView对象,并确保它们的大小和坐标是相同的。我设置布局约束,它们都是相同的高度和宽度,并且两者与相邻元素的距离相同。我还让UILabel变得透明。在此之后,我只是将渐变作为子层添加到UIView中,并且它工作得非常好。

相关问题