26
votes

I had a similar problem to this poster. And I used jrturton's suggestion to move the code for customizing the buttons into viewDidLayoutSubviews. It was working well until I received this error:

'NSInternalInconsistencyException', reason: 'Auto Layout still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation needs to send -layoutSubviews to the view to invoke auto layout.'

I'm very clueless on graphics, and the only thing I could think of was to put [self.view layoutSubviews]; but that didn't fix anything. It worked when I unchecked "Auto Layout" in my Storyboard, but that changed the dimensions of my buttons, and I was wondering if there was another way to fix it?

Code:

-(void)viewDidLayoutSubviews {
    NSArray *arrayOfButtons = [NSArray arrayWithObjects:self.decimalButton, self.buttonOne, self.buttonTwo, self.buttonThree, nil];

    for (UIButton *button in arrayOfButtons) {

        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];

        button.layer.borderWidth = 0.25f;
        button.layer.borderColor = [[UIColor grayColor] CGColor];

        CAGradientLayer *btnGradient = [CAGradientLayer layer];
        btnGradient.frame = button.bounds;
        btnGradient.colors = [NSArray arrayWithObjects:
                              (id)[[UIColor colorWithRed:122.0f / 255.0f green:188.0f / 255.0f blue:255.0f / 255.0f alpha:1.0f] CGColor],
                              (id)[[UIColor colorWithRed:96.0f / 255.0f green:171.0f / 255.0f blue:248.0f / 255.0f alpha:1.0f] CGColor],
                              nil];
        [button.layer insertSublayer:btnGradient atIndex:0];
    }
}
1
What about calling [super viewDidLayoutSubviews]? The docs say the default implementation does nothing, but worth a try. - Chris Wagner

1 Answers

66
votes

I had this issue recently, when I wanted to programmatically adjust frame of the view created by storyboard, by providing a viewDidLayoutSubviews message handler. Following the instruction from exception message, I tried to add [self.view layoutIfNeeded] at the end of -viewDidLayoutSubviews, and then it worked.