请你协助,我已经创建了一个渐变,我已添加到一个按钮,但现在我使用故事板设置的按钮图像不再显示。我的代码如下:
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
答案 0 :(得分:8)
您可以使用bringSubview(toFront:)
将按钮imageView
移至top position
if let imageView = button.imageView {
productsAndServicesButton.bringSubview(toFront: imageView)
}
答案 1 :(得分:0)
作为@Oleh答案的替代方法,您可以将内容添加到渐变层,例如,
gradient.contents = imageView.image?.cgImage