如何在 iOS swift 中的 UIButton 上设置渐变?

Tec*_*ain 4 gradient uibutton ios swift

我有一个 UIButton。我想设置按钮的渐变如下。

在此处输入图片说明

我试过下面的代码,但它没有按照屏幕截图设置颜色。

 func applyGradient(colours: [UIColor]) -> Void {
        self.applyGradient(colours: colours, locations: nil)
    }

    func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        gradient.locations = locations
        self.layer.insertSublayer(gradient, at: 0)
    }
Run Code Online (Sandbox Code Playgroud)

PGD*_*Dev 7

你可以简单地这样做:

extension UIButton
{
    func applyGradient(colors: [CGColor])
    {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}
Run Code Online (Sandbox Code Playgroud)

设置渐变UIButton

self.button.applyGradient(colors: [UIColor.green.cgColor, UIColor.black.cgColor])
Run Code Online (Sandbox Code Playgroud)