将UIButton的背景设置为CAGradientLayer

时间:2019-05-28 08:24:42

标签: swift xcode

如何将UIButton的背景设置为CAGradientLayer?

我尝试了以下方法:

func applyGradient(colors: [UIColor], locations: [NSNumber]?) -> Void {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colors.map { $0.cgColor }
    gradient.locations = locations
    self.layer.insertSublayer(gradient, at: 0)
}
我从Set Background Gradient on Button in Swift那里得到的

然后使用它:

let startButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Get Started", for: .normal)
    button.setTitleColor(AppSettings.PURPL_COLOR, for: .normal)
    button.titleLabel?.font = UIFont(name: "Rubik-Medium", size: 16.0)
    return button
}()

startButton.applyGradient(colors: [.red, .blue], locations: nil)

此外,我将按钮的宽度设置为视图的宽度,并将高度设置为50。

但是,当我运行它时,这就是我得到的:

result

未应用背景渐变。

1 个答案:

答案 0 :(得分:1)

调用方法Bounds时,按钮的

applyGradient将为0。因此,创建一个UIButton子类并在frame方法中更改渐变层layoutSublayers

class GradientButton: UIButton {
    let gradient: CAGradientLayer = CAGradientLayer()
    internal override init(frame: CGRect) {
        super.init(frame: frame)
    }
    internal required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    required init(_ colors: [UIColor], locations: [NSNumber]?) {
        super.init(frame: .zero)
        applyGradient(colors,locations:locations)
    }
    func applyGradient(_ colors: [UIColor], locations: [NSNumber]?) {
        gradient.colors = colors
        gradient.locations = locations
        gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        layer.insertSublayer(gradient, at: 0)
    }
    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        gradient.frame = self.bounds
    }
}

并使用颜色和位置值创建按钮

let button = GradientButton([.red,.blue], locations: nil)