Question

I'm trying to customize grouped UITableViewCell's backgroundView with a gradient, based on code I find on this blog. It's a subclass of UIView for use on cell.backgroundView.

The colors of the background's gradient are defined like this on the original code :

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

And then, used like this on the drawRect of the subclassed backgroundView:

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

I'm trying to implement a function to set start and end color for the gradient, which takes two UIColors and then fill in a global float array float startAndEndColors[8] (in .h / @interface) for later use:

-(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};
}

But it throw me this error "Expected expression" at assignation.

I tried with CGFloat, desperately adding random const, but I quickly ran out of ideas.

I simply don't get it, why can't I fill my float array this way? What am I doing wrong?

Was it helpful?

Solution

Comment added as answer:

The only way of creating an array that way is dynamically in code. If you are adding to an iVar (class variable) you need to go through one by one because the memory has already been allocated at initialization. So use startAndEndColors[0] = ..., etc.

As for your follow up question: No, there is no way to assign values in that way to memory that has already been initialized in the allocation phase. If you used std::vector or other objects then it would be possible.

A way around that would be something like this in your header

CGFloat *startAndEndColors;

And then something like this in your implementation

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

That way you can initialize it the way you want to, but you have no guarantee of the number of objects in your startAndEndColors object. You could later assign it to something of the wrong size and cause crashes if you try to access outside of it's bounds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top