Search code examples
iosswiftxcodexcode-storyboard

Changing constant of a size-classed constraint within code but it reverts back to storyboard value


I’m running into an issue with constraints that use size classes.

Within the storyboard, I’m setting a view's width constraint to different values for compact width and regular width size classes. Within the view controller, I have a reference to that constraint where I’m setting its constant to zero within viewDidLoad().

The problem that I’m having is that the constant for the constraint reverts back to the storyboard value, except after viewDidAppear() gets called. After that point, the constraint constant remains at whatever value I set it to within the source code.

Even setting the constraint's constant to zero within viewWillAppear() still leads to the constraint reverting back to the storyboard value.

I can remove the constraint from the storyboard and do it in code, but I was wondering if anyone had any other ideas as to why this is happening and if there is a fix that doesn't involve having to remove the constraint from the storyboard.


Solution

  • I guess autolayout lays everything out using the default constraints and then lays everything out again, accounting for size classes, before the view appears. That’s why the constraint “reverts” - it’s really just being set to the correct value for the size class for the first time.

    Anyways, calling view.layoutIfNeeded() within viewDidLoad() before modifying the constraint solved the issue.