2

I faced strange behavior. I'm using custom styled button which I setup in my controller:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.signOutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.signOutButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];

    CAGradientLayer *btnGradient = [CAGradientLayer layer];
    btnGradient.frame = self.signOutButton.bounds;
    btnGradient.colors = [NSArray arrayWithObjects:
                          (id)[[UIColor colorWithRed:102.0f / 255.0f green:102.0f / 255.0f blue:102.0f / 255.0f alpha:1.0f] CGColor],
                          (id)[[UIColor colorWithRed:51.0f / 255.0f green:51.0f / 255.0f blue:51.0f / 255.0f alpha:1.0f] CGColor],
                          nil];

    [self.signOutButton.layer insertSublayer:btnGradient atIndex:0];
}

It works OK in iOS 5. But if I'm building this for iOS 6 with enabled Autolayout for Storyboard then gradient in my style disappears/becomes transparent (but title is still visible).

If I'm disabling autolayout - gradient is back. Could somebody explain such behavior with autolayout?

Oleksandr
  • 419
  • 3
  • 14

1 Answers1

10

In viewDidLoad, under autolayout, your views will not yet have a frame, so you are making the layer have a frame of CGRectZero.

You need to move this code, or at least the part where you set the frame of the gradient layer, to viewDidLayoutSubviews or similar.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • ViewDidLayoutSubviews is called on each rotation of the device so the buttons would be refreshing their properties. Is there a more efficient place for this other than using a BOOL flag or something? – GeoffCoope Feb 13 '13 at 01:03
  • Is it causing you performance problems? Compared to everything else that happens on rotation, I would imagine this is pretty minor. You could always check the layer's frame before setting it. – jrturton Feb 13 '13 at 07:44
  • Agreed, It's probably a minor performance hit but still a hit non the less. On my app I set a boolean flag when it runs for the first time so it only updates the UI once as my users will be rotating the screen all over the place and I have several gradients being updated. – GeoffCoope Feb 13 '13 at 11:53