John
John

Reputation: 95

Gradient layer not showing up/working on an existing View

I have a view with has another view (called swipeView) inside it. I'm trying to gradient color it using the CAGradientLayer - the code is below

CAGradientLayer *layer = [CAGradientLayer layer];

layer.colors = [NSArray arrayWithObjects:(id)[UIColor darkGrayColor].CGColor, 
                  [UIColor lightGrayColor].CGColor, nil];

layer.frame = swipeView.bounds;

[swipeView.layer insertSublayer:layer atIndex:0];

I'm calling this in the ViewDidLoad method of the main view controller. I see no effect - the view I'm trying to color remains just the same. What am I doing wrong? Are there any other settings/ordering etc. I should know about?

Upvotes: 1

Views: 2354

Answers (4)

Tim Closs
Tim Closs

Reputation: 546

You don't need the nil terminator at the end of the colors array.

Also, I found insertSublayer did not work, with index either 0 or 1. Changing to simply addSublayer did the trick.

Upvotes: 0

Joshua Frank
Joshua Frank

Reputation: 13838

I don't know if this is the problem you're having, but I was just having the exact same symptom, and after a few hours of bafflement, I discovered my problem: I was creating a button, adding the gradient layer, and only later positioning the button. Initially, the button dimensions are all 0, and when setting layer.frame = swipeView.bounds; I was setting the gradient layer to have 0 dimensions too. I added code so that when sizing the button, I also sized the sublayers to match, and this fixed the problem. I'm actually using MonoTouch, so the code looks like this:

btn.Frame = new RectangleF([the dimensions you need]);

foreach(var s in btn.Layer.Sublayers)
{
   s.Frame = btn.Bounds;
}

Maybe you're creating a view in code, and the view hasn't been sized or positioned, and so when you add the gradient it also has no size, and that's why you can't see it. When the view changes size (in ViewDidLayoutSubviews maybe), resize the gradient layer and see if that solves it.

Upvotes: 3

fibnochi
fibnochi

Reputation: 1113

CAGradientLayer *layer = [CAGradientLayer layer];

layer.colors = [NSArray arrayWithObjects:(id)[UIColor darkGrayColor].CGColor, 
              (id)[UIColor lightGrayColor].CGColor, nil];

layer.frame = swipeView.bounds;

[swipeView.layer insertSublayer:layer atIndex:0];

Make sure that swipeView is not nil and try swipeView.frame.

Upvotes: 0

Jason Foreman
Jason Foreman

Reputation: 2146

That should work. Are you sure you hooked up your swipeView outlet correctly? Debug your -viewDidLoad and verify that swipeView is not nil. Also double check that the bounds (layer.frame) is something sensible.

It shouldn't be necessary, but you can try throwing in a [layer setNeedsDisplay] just to force the layer to render again, but I don't think that is your issue here.

Upvotes: 0

Related Questions