我正在使用自动布局。我有三个UIButton
占据了整个屏幕。每个UIButton都有不同的背景颜色,我想为每个添加渐变。
以下是我采取的步骤:
UIButton
名为CustomButton
CustomButton
。Identity Inspector
@IBInspectable
属性。以下是我在CustomButton中配置渐变的方法:
import UIKit
@IBDesignable class CustomButton: UIButton {
@IBInspectable var topColor: UIColor!
@IBInspectable var bottomColor: UIColor!
override func drawRect(rect: CGRect) {
let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
let gradientLocations: [Float] = [0.0, 1.0]
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
self.layer.addSublayer(gradientLayer)
}
}
然而,渐变仍未显示。我做错了什么?
更新
这也不起作用:
import UIKit
@IBDesignable class CustomButton: UIButton {
@IBInspectable var topColor: UIColor!
@IBInspectable var bottomColor: UIColor!
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
let gradientLocations: [Float] = [0.0, 1.0]
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
gradientLayer.frame = self.bounds
self.layer.addSublayer(gradientLayer)
}
}
答案 0 :(得分:0)
首先,不要在-drawRect
中创建图层 - 它用于绘制到当前的Core Graphics上下文中,并且可以多次调用,这将导致每次都创建一个新的渐变图层。相反,覆盖-initWithCoder:
并在那里创建图层。
你的图层根本没有显示的原因是因为它的框架没有设置并且默认为CGRectZero
,即一个0✕0的矩形。创建图层时,您应该将其frame
设置为视图的bounds
。如果视图要更改大小,您还应该覆盖-layoutSubviews
并在那里更新图层的框架。