Andrew Lauer Barinov
Andrew Lauer Barinov

Reputation: 5754

Memory Errors when using CAGradientLayer

I am using CAGradientLayer to create a background layer, as described in this answer to this question: Gradients on UIView and UILabels On iPhone

However when I use this code I get a exc_bad_access error with a reference to CGColorSpaceGetModel.

UILabel *headerText = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width -10, 18)];    

CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.bounds = headerText.bounds;

UIColor *topColor = [[UIColor alloc] initWithRed:0.5647 green:0.6235 blue:0.6667 alpha:1.0];

UIColor *bottomColor = [[UIColor alloc] initWithRed:0.7216 green:0.7569 blue:0.7843 alpha:1.0];

NSArray *gradientColors = [[NSArray alloc] initWithObjects:topColor, bottomColor, nil];

gradient.colors = gradientColors;

[headerText.layer insertSublayer:gradient atIndex:0];

Any idea what could be causing this error?

Upvotes: 0

Views: 844

Answers (3)

Simon Lee
Simon Lee

Reputation: 22334

You need to use CGColorRefs not UIColor... there is a property on UIColor to get the CGColorRef....

NSArray *gradientColors = [[NSArray alloc] initWithObjects:(id)topColor.CGColor, (id)bottomColor.CGColor, nil];

Upvotes: 6

vikingosegundo
vikingosegundo

Reputation: 52237

gradient.colors need to be CGColor, not UIColor.

try

NSArray *gradientColors = [[NSArray alloc] initWithObjects:(id)topColor.CGColor, (id)bottomColor.CGColor, nil];

Upvotes: 1

Eugene
Eugene

Reputation: 10045

Use CGColor instead of UIColor:

    NSArray *gradientColors = [[NSArray alloc] initWithObjects:topColor.CGColor, 
bottomColor.CGColor, nil];

Upvotes: 0

Related Questions