0

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.

mdaigle
  • 303
  • 3
  • 8
  • It sounds like it's related to the view lifecycle. Have you tried coding it in a later override? Maybe `viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)`? That's the override where you would code against size classes if you weren't using IB. –  Jul 19 '17 at 22:12

2 Answers2

1

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.

mdaigle
  • 303
  • 3
  • 8
0

It is an expected behaviour, since a view width is not known at viewDidLoad()

Check out this related answer https://stackoverflow.com/a/16421170/7626803

0rt
  • 1,325
  • 2
  • 17
  • 25