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

问题描述 投票:0回答:2

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

enter image description here

我尝试了下面的代码,但没有根据屏幕截图设置颜色。

 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)
    }
ios swift uibutton gradient
2个回答
2
投票

你可以简单地这样做:

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)
    }
}

UIButton上设置渐变:

self.button.applyGradient(colors: [UIColor.green.cgColor, UIColor.black.cgColor])

-1
投票

上面的代码适合我,创建扩展是好的,因为渐变可以应用于多个按钮

如果需要为渐变添加角半径,则需要在上面的代码中只添加一行代码

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
        gradientLayer.cornerRadius = self.frame.size.height / 2
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.