如何在后台为UIButton设置渐变颜色?

时间:2018-09-26 05:20:26

标签: ios uibutton gradient linear-gradients cagradientlayer

我正在尝试为UIButton设置 CAGradientLayer

但是并没有完全正确。我做错了吗?

我获得

之类的 输出

this

您会看到一条水平线

这是我尝试的代码

let topColor = UIColor(red: 0.62, green: 0.38, blue: 1, alpha: 1).cgColor
let bottomColor = UIColor(red: 0.87, green: 0.51, blue: 0.93, alpha: 1).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = myButton.bounds
gradientLayer.colors = [topColor, bottomColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
myButton.layer.insertSublayer(myButton, at: 0)

2 个答案:

答案 0 :(得分:2)

像这样创建一个可设计的自定义类

import Foundation
import  UIKit
@IBDesignable class CustomButton:UIButton {

    @IBInspectable var firstColor:UIColor = UIColor.clear {
        didSet {
            updateUI()
        }
    }
    @IBInspectable var secondColor:UIColor = UIColor.clear {
        didSet{
            updateUI()
        }
    }

    override class var layerClass: AnyClass {
        get {
            return CAGradientLayer.self
        }
    }
    func updateUI(){
        let gradient: CAGradientLayer = self.layer as! CAGradientLayer
        gradient.frame = self.bounds
        gradient.colors = [firstColor,secondColor].map { $0.cgColor }
        gradient.locations = [0.0,1.0]
        gradient.startPoint =  CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

    }
}
从您的身份检查器中

像这样将UIbutton类设置为CustomButtom enter image description here

从属性检查器中将渐变颜色更改为您要设置的enter image description here

最后,您的按钮将如下所示 enter image description here

如果要将起点和终点更改为这些颜色 只需使用这两个值

gradient.startPoint = CGPoint(x:0.0,y:1.0)      gradient.endPoint = CGPoint(x:1.0,y:1.0)

答案 1 :(得分:0)

布局视图时,您必须更新渐变的框架:

override func viewDidLayoutSubviews() {
    myButton.layer.sublayers?.first?.frame = myButton.bounds
}