Search code examples
iosuibuttonios6custom-controlsgradient

Can't do custom UIButton in iOS6 with enabled storyboard autolayout


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?


Solution

  • 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.