我在UIButton上附加了一个渐变类,渐变显示得很好。但是,UIButton的标题或文本未显示。似乎渐变覆盖了文本。这是我的代码:
@IBDesignable
class GradientView: UIButton {
@IBInspectable var topColor: UIColor = #colorLiteral(red: 1, green: 0.0318463631, blue: 0, alpha: 1) {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable var bottomColor: UIColor = #colorLiteral(red: 1, green: 0.4265971184, blue: 0, alpha: 1) {
didSet {
self.setNeedsLayout()
}
}
override func layoutSubviews() {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.frame = self.bounds
gradientLayer.cornerRadius = layer.cornerRadius
self.layer.insertSublayer(gradientLayer, at: 0)
}
//Rounded Button Functions
@IBInspectable var cornerRadius : CGFloat = 3.0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
override func awakeFromNib() {
self.setupView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.setupView()
}
func setupView() {
self.layer.cornerRadius = cornerRadius
}
@IBInspectable var border : CGFloat = 1.0 {
didSet {
self.layer.borderWidth = border
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
}
我不知道问题是什么。我将此代码用于另一个项目,它显示正常。 谢谢
答案 0 :(得分:3)
您忘记在super.layoutSubviews()
中呼叫layoutSubviews()
。
override func layoutSubviews() {
super.layoutSubviews()
// your code
}