When can I activate/deactivate layout constraints?

2020-01-27 19:46发布

I've set up multiple sets of constraints in IB, and I'd like to programmatically toggle between them depending on some state. There's a constraintsA outlet collection all of which are marked as installed from IB, and a constraintsB outlet collection all of which are uninstalled in IB.

I can programmatically toggle between the two sets like so:

NSLayoutConstraint.deactivateConstraints(constraintsA)
NSLayoutConstraint.activateConstraints(constraintsB)

But... I can't figure out when to do that. It seems like I should be able to do that once in viewDidLoad, but I can't get that to work. I've tried calling view.updateConstraints() and view.layoutSubviews() after setting the constraints, but to no avail.

I did find that if I set the constraints in viewDidLayoutSubviews everything works as expected. I guess I'd like to know two things...

  1. Why am I getting this behavior?
  2. Is it possible to activate/deactivate constraints from viewDidLoad?

8条回答
相关推荐>>
2楼-- · 2020-01-27 20:20

You can also adjust the priority property to "enable" and "disable" them (750 value to enable and 250 to disable for example). For some reason changing the active BOOL didn't had any effect on my UI. No need for layoutIfNeeded and can be set and changed at viewDidLoad or any time after that.

查看更多
闹够了就滚
3楼-- · 2020-01-27 20:24

When a view is being created the following life cycle methods are called in order:

  1. loadView
  2. viewDidLoad
  3. viewWillAppear
  4. viewWillLayoutSubviews
  5. viewDidLayoutSubviews
  6. viewDidAppear

Now to your questions.

  1. Why am I getting this behavior?

Answer: Because when you try to set the constraints on the views in viewDidLoad the view does not have its bounds, hence constraints cannot be set. It's only after viewDidLayoutSubviews that the view's bounds are finalized.

  1. Is it possible to activate/deactivate constraints from viewDidLoad?

Answer: No. Reason explained above.

查看更多
登录 后发表回答