2016-01-13 53 views
1

我有這個陣列的UIColors這裏陣列的UIColor標問題的

let newLayer = CALayer() 

let barColors = [ 
    //Red 
    UIColor(red: 0.969, green: 0.49, blue: 0.443, alpha: 1), 
    //Orange 
    UIColor(red: 0.984, green: 0.647, blue: 0.431, alpha: 1), 
    //Pink 
    UIColor(red: 0.894, green: 0.592, blue: 0.698, alpha: 1), 
    //Purple 
    UIColor(red: 0.851, green: 0.6, blue: 0.957, alpha: 1), 
    //Yellow 
    UIColor(red: 0.98, green: 0.875, blue: 0.455, alpha: 1), 
    //Green 
    UIColor(red: 0.49, green: 0.792, blue: 0.616, alpha: 1), 
    //Blue 
    UIColor(red: 0.553, green: 0.71, blue: 0.906, alpha: 1)] 

當我嘗試我newLayer背景顏色分配給UIColors的一個數組中與此:

newLayer.backgroundColor = barColors[0] 

我得到一個錯誤,說cannot subscript a value of type '[UIColor]'。任何想法,爲什麼我得到這個錯誤,以及如何解決它?

+5

''CALayers's財產backgroundColor'是'CGColor',而不是一個'的UIColor ' –

+0

我很好奇爲什麼Swift編譯器認爲這是一個下標問題......也許它認爲程序員可以「修改」Swift結構體'Array '的代碼,以便它的'subscript'返回期望的'CGColor'的實例? –

回答

2

錯誤具有誤導性。 backgroundColorCALayer的性質預計CGColor類型的值不是UIColor

您可以從UIColor得到CGColor值:

newLayer.backgroundColor = barColors[0].CGColor 
1

試試這個

newLayer.backgroundColor = barColors[0].CGColor 

因爲CALayer'sbackgroundColor屬性接受CGColor值,而不是UIColor

+0

完美謝謝! – OriginalAlchemist

-1

試試這個,我覺得它將幫助你,如果你想設置viewcontroller的視圖的背景顏色。

let newLayer = CALayer() 

    let barColors = [ 
     //Red 
     UIColor(red: 0.969, green: 0.49, blue: 0.443, alpha: 1), 
     //Orange 
     UIColor(red: 0.984, green: 0.647, blue: 0.431, alpha: 1), 
     //Pink 
     UIColor(red: 0.894, green: 0.592, blue: 0.698, alpha: 1), 
     //Purple 
     UIColor(red: 0.851, green: 0.6, blue: 0.957, alpha: 1), 
     //Yellow 
     UIColor(red: 0.98, green: 0.875, blue: 0.455, alpha: 1), 
     //Green 
     UIColor(red: 0.49, green: 0.792, blue: 0.616, alpha: 1), 
     //Blue 
     UIColor(red: 0.553, green: 0.71, blue: 0.906, alpha: 1)] 
    self.viewIfLoaded?.backgroundColor = barColors[0]; // index for color 

此外,如果你想要的setBackground顏色的視層,然後找到下面的代碼將有助於

newLayer.backgroundColor = barColors[0].CGColor;