ios - Swift:向按钮添加渐变后按钮图像不显示

标签 ios swift swift3 storyboard

请帮忙,我已经创建了一个渐变,我已经添加到一个按钮,但现在我使用 Storyboard 设置的按钮图像不再显示。我的代码如下:

import UIKit

class MenuViewController: UIViewController {

    @IBOutlet weak var productsAndServicesButton: UIButton!

       override func viewDidLoad() {
        super.viewDidLoad()

        let bg = CAGradientLayer().redBackgroundGradient()
        bg.frame = self.productsAndServicesButton.bounds
        self.productsAndServicesButton.layer.insertSublayer(bg, at: 0)

   }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

实际实现渐变的带函数代码如下:

import UIKit

extension CAGradientLayer {

    func redBackgroundGradient() -> CAGradientLayer{
        let startColor =  UIColor(red:0.82, green:0.13, blue:0.19, alpha:1.0)
        let centreColor = UIColor(red:0.65, green:0.04, blue:0.10, alpha:1.0)
        let endColor = UIColor(red:0.56, green:0.04, blue:0.09, alpha:1.0)

        let gradientColors : [CGColor] = [startColor.cgColor,centreColor.cgColor,endColor.cgColor]
        let gradientLocations : [Float] = [0.0,0.5,1.0]
        let gradientLayer : CAGradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientColors
        gradientLayer.locations = gradientLocations as [NSNumber]?

        return gradientLayer
    }


}

我希望图像出现在渐变之上,如下所示

the red will be the gradient and the white image is the one i want to display

最佳答案

您可以使用 bring​Subview(to​Front:​) 将按钮的 imageView 移动到 顶部位置

if let imageView = button.imageView {
    productsAndServicesButton.bringSubviewToFront(imageView)
}

关于ios - Swift:向按钮添加渐变后按钮图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206280/

相关文章:

ios - UIAlertView 弹出窗口不允许我向上滑动控制中心

reference - Swift 中的异常行为 : constant defined with LET but behaving like a variable defined with VAR

ios - 迅速在iOS中检索json数据

ios - 当 Leaks 工具不显示内存泄漏时如何调试它们?

ios - 在 Swift 3 中没有更多上下文的表达式类型不明确

swift - UITableView 未显示正确的行数

ios - 在哪里为使用 SwiftUI 的用户初始化 sqlite 数据库?

objective-c - 从 UIViewController 内部在 iOS objective-c 中绘制 4.000 个点或线

ios - 仅适用于 iPhone 的方向锁定

ios - Swift 自定义 UITableViewCell 标签始终为零