2017-10-06 52 views
0

我有一個項目,它包含了一些UIStackView中的按鈕。每個按鈕都有一個backgroundImage。一切都按照需要進行渲染,但是我想在背景圖像的前面放置一個半透明的漸變圖層,以便按鈕上的文本具有更多的對比度。在UIButton的背景上添加一個漸變圖層

我試圖用這個代碼viewDidLoad,在每個的UIButton的將backgroundImage前加上一個半透明漸變:

buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour] 
let gradientLayer = CAGradientLayer() 
gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5)] 
// gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5).cgColor] 
// gradientLayer.colors = [UIColor.orange] 
// gradientLayer.colors = [UIColor.orange.cgColor] 
buttonArray.forEach({$0.imageView?.layer.insertSublayer(gradientLayer, at: 0)}) 

因爲它的立場,沒有被添加。我嘗試將顏色更改爲沒有alpha值的顏色,並將所需的顏色更改爲.cgColor。沒有骰子。謝謝你的閱讀。我歡迎你的建議,如何在UIButton的backgroundImage前放置一個gradientLayer。

我根據我嘗試過的代碼中發現here

+0

有你試圖添加層圖像,然後你分配這個圖像作爲你的背景圖像? – antonio081014

+0

好主意。我會給它一個旋轉 – Adrian

回答

0

我認爲你必須指定一個以上的顏色,還有層的界限:

let buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour] 

    for button in buttonArray { 
     let gradientLayer = CAGradientLayer() 
     gradientLayer.colors = [UIColor(white: 0.5, alpha: 0.5).cgColor, UIColor(white: 1.0, alpha: 0.5).cgColor] 
     gradientLayer.frame = (button?.bounds)! 
     button?.layer.insertSublayer(gradientLayer, at: 0) 
    } 
+0

謝謝你的閱讀。這對我沒有用。 – Adrian