2013-07-11 33 views
0

我想用漸變自定義分組的UITableViewCell的backgroundView,基於我找到的代碼on this blog.它是用於cell.backgroundView的UIView的子類。浮動指派到全局數組

背景的漸變的顏色被這樣限定在原來的代碼:

#define TABLE_CELL_BACKGROUND { 1, 1, 1, 1, 0.866, 0.866, 0.866, 1}   // #FFFFFF and #DDDDDD 

然後,像這樣使用的子類backgroundView的drawRect

CGFloat components[8] = TABLE_CELL_BACKGROUND; 
myGradient = CGGradientCreateWithColorComponents(myColorspace, components , locations, 2); 

我試圖實現一個函數來設置漸變的開始和結束顏色,這需要兩個UIColors,然後填充全局浮點數組float startAndEndColors[8](在.h/@interface中)供以後使用:

-(void)setColorsFrom:(UIColor*)start to:(UIColor*)end{ 

    float red = 0.0, green = 0.0, blue = 0.0, alpha =0.0, red1 = 0.0, green1 = 0.0, blue1 = 0.0, alpha1 =0.0; 

    [start getRed:&red green:&green blue:&blue alpha:&alpha]; 
    [end getRed:&red1 green:&green1 blue:&blue1 alpha:&alpha1]; 

    //This line works fine, my array is successfully filled, just for test 
    float colorsTest[8] = {red, green, blue, alpha, red1, green1, blue1, alpha1}; 

    //But for this one, I just have an error. 
    //"Expected expression" 
    //     \ 
    //     v 
    startAndEndColors = {red, green, blue, alpha, red1, green1, blue1, alpha1}; 
} 

但是在賦值時它拋出了這個錯誤「Expected expression」。

我試着用CGFloat,拼命地加入隨機const,但我很快跑出了想法。

我簡直不明白,爲什麼我不能用這種方式填充我的float數組?我究竟做錯了什麼?

+1

以這種方式在代碼中動態創建數組的唯一方法。如果你正在添加一個iVar(類變量),你需要逐個進行,因爲內存已經在初始化時被分配了。所以使用'startAndEndColors [0] = ...'等 – Putz1103

+0

它的工作,謝謝!但是沒有辦法象我用colorsTest一樣添加所有這些值嗎?請將您的評論轉換爲答案,我會接受它。 – Bigood

回答

1

添加的評論爲答案:

以這種方式在代碼中動態創建數組的唯一方法。如果你正在添加一個iVar(類變量),你需要逐個進行,因爲內存已經在初始化時被分配了。因此,使用startAndEndColors[0] = ...等。

至於你的後續問題:不,沒有辦法將值分配給已經在分配階段初始化的內存。如果你使用std :: vector或其他對象,那麼它是可能的。

圍繞一個方法是這樣的在你的頭

CGFloat *startAndEndColors; 

然後像這樣在您的實現

float colorsTest[8] = {red, green, blue, alpha, red1, green1, blue1, alpha1}; 
startAndEndColors = colorsTest; 

這樣,您可以初始化它,你想要的方式,但是您無法保證startAndEndColors對象中的對象數量。您稍後可以將其分配給錯誤的大小,並且如果您嘗試訪問超出限制範圍,則會導致崩潰。

+0

確實,你的第二個主張似乎有效。此外,當'startAndEndColors'爲'CGFloat *'時,可以直接指定'startAndEndColors =(float []){紅色,綠色,藍色,alpha,red1,green1,blue1,alpha1} – Bigood