如何在背景按钮 中放置渐变包含系统图像?

How to put a gradient in a background button witch contains a system image?

我有一个带系统图片的按钮:

@IBOutlet weak var ampouleButton: UIButton!

在 viewdid 加载中,我把这个:

let ampouleButtonConfig = UIImage.SymbolConfiguration(
            pointSize: 30,
            weight: .regular,
            scale: .large)
        
        let ampouleButtonImage = UIImage(
            systemName: "lightbulb",
            withConfiguration: ampouleButtonConfig)
        
        ampouleButton.backgroundColor = Theme.gold03 // i need to put here a gradient
        ampouleButton.setImage(ampouleButtonImage, for: .normal)
        ampouleButton.tintColor = Theme.blanc
        ampouleButton.layer.cornerRadius = ampouleButton.frame.height / 2
        ampouleButton.layer.shadowOpacity = 0.4
        ampouleButton.layer.shadowRadius = 3
        ampouleButton.layer.shadowOffset =
            CGSize(width: 0, height: 5)
        ampouleButton.alpha = 1

我需要添加渐变而不是背景颜色。

我测试了这个但是没有用:

let gradientLayer = CAGradientLayer()
            gradientLayer.frame = self.ampouleButton.bounds
            gradientLayer.colors = [UIColor.yellow.cgColor, UIColor.white.cgColor]
        ampouleButton.layer.insertSublayer(gradientLayer, at: 0)

实际上,按钮图像位于图层后面。试试这个:

extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = .init(x: 0.5, y: 0), endGradient: CGPoint = .init(x: 0.5, y: 1)) {
        // check first if there is already a gradient layer to avoid adding more than one
            let gradientLayer = CAGradientLayer()
            gradientLayer.cornerRadius = radius
            gradientLayer.colors = colors
            gradientLayer.startPoint = startGradient
            gradientLayer.endPoint = endGradient
            gradientLayer.frame = bounds
            layer.insertSublayer(gradientLayer, at: 0)
    }
}

并在 viewDidLoad 中放置:

ampouleButton.applyGradient(colors: [Theme.bleu!.cgColor, Theme.softBlue!.cgColor], radius: self.ampouleButton.frame.height / 2, startGradient: CGPoint(x: 0, y: 0.5), endGradient: CGPoint(x: 1, y: 0)) 
if let imgView = ampouleButton.imageView { ampouleButton.bringSubviewToFront(imgView) }

从这里找到 applyGradient 函数: