我什么时候可以激活/停用布局约束? [英] When can I activate/deactivate layout constraints?

查看:34
本文介绍了我什么时候可以激活/停用布局约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 IB 中设置了多组约束,我想根据某些状态以编程方式在它们之间切换.有一个 constraintsA 出口集合,它们都被标记为从 IB 安装,还有一个 constraintsB 出口集合,它们都在 IB 中卸载.

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)

但是……我不知道什么时候应该这样做.看起来我应该能够在 viewDidLoad 中做到这一点,但我无法让它工作.我尝试在设置约束后调用 view.updateConstraints()view.layoutSubviews() ,但无济于事.

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.

我确实发现,如果我在 viewDidLayoutSubviews 中设置约束,一切都会按预期进行.我想我想知道两件事......

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. 为什么我会出现这种行为?
  2. 是否可以从 viewDidLoad 激活/停用约束?

推荐答案

我在 viewDidLoad 中激活和停用 NSLayoutConstraints,我没有任何问题.所以它确实有效.您的应用程序和我的应用程序之间的设置肯定有所不同:-)

I activate and deactivate NSLayoutConstraints in viewDidLoad, and I do not have any problems with it. So it does work. There must be a difference in setup between your app and mine :-)

我将只描述我的设置 - 也许它可以为您提供线索:

I'll just describe my setup - maybe it can give you a lead:

  1. 我为我需要激活/停用的所有约束设置了 @IBOutlets.
  2. ViewController 中,我将约束保存到不弱的类属性中.这样做的原因是我发现在取消激活一个约束后,我无法重新激活它——它是零.因此,它似乎在停用时被删除.
  3. 我不像你那样使用 NSLayoutConstraint.deactivate/activate,我使用 constraint.active = YES/NO 代替.莉>
  4. 设置约束后,我调用view.layoutIfNeeded().
  1. I set up @IBOutlets for all the constraints that I need to activate/deactivate.
  2. In the ViewController, I save the constraints into class properties that are not weak. The reason for this is that I found that after deactivating a constraint, I could not reactivate it - it was nil. So, it seems to be deleted when deactivated.
  3. I do not use NSLayoutConstraint.deactivate/activate like you do, I use constraint.active = YES/NO instead.
  4. After setting the constraints, I call view.layoutIfNeeded().

这篇关于我什么时候可以激活/停用布局约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆