iOS8:使用IB向UIButton添加渐变

时间:2015-07-06 21:53:15

标签: ios8 uibutton storyboard autolayout

我正在使用自动布局。我有三个UIButton占据了整个屏幕。每个UIButton都有不同的背景颜色,我想为每个添加渐变。

以下是我采取的步骤:

  1. Subclassed UIButton名为CustomButton
  2. CustomButton
  3. 中分配了每个按钮Identity Inspector
  4. 在CustomButton类中,我声明了两个@IBInspectable属性。
  5. 我通过IB传递这些颜色。
  6. 以下是我在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)
        }
    }
    

1 个答案:

答案 0 :(得分:0)

首先,不要在-drawRect中创建图层 - 它用于绘制到当前的Core Graphics上下文中,并且可以多次调用,这将导致每次都创建一个新的渐变图层。相反,覆盖-initWithCoder:并在那里创建图层。

你的图层根本没有显示的原因是因为它的框架没有设置并且默认为CGRectZero,即一个0✕0的矩形。创建图层时,您应该将其frame设置为视图的bounds。如果视图要更改大小,您还应该覆盖-layoutSubviews并在那里更新图层的框架。