Search code examples
iosswiftuikitnslayoutconstraint

Toggling a constraint under a certain condition


Setup: I have designed an UIButton with a bottom constraint X, priority 999. In addition to this constraint the UIButton also has another constraint Y, priority 1000 but this one is marked installed = false.

Y is being linked to an @IBOutlet in my UIViewController with a strong reference.

On viewDidLoad(): If a given condition happens to be true, I activate constraint Y by doing Y.isActive = true, and then view.layoutIfNeeded(), which eventually calls updateConstraints() if needed. If the condition is false, I do nothing.

My expectation: when the condition is true, I expect the view to apply the Y constraint to the button and drop X. When the condition is false, I expect the UIButton to only have constraint X.

The result: It seems like constraint Y is not being applied at all, even when the condition is met.

I would appreciate any thoughts on this, this to me seems like something that should work.

Thanks.

P.S. I use swift, but I don't mind if the answer provided is in Obj-C.


Solution

  • There seems to be a bug when using IB, where setting the property of a constraint as uninstalled will not always work properly as being 'inactive' but rather it will later create problems when activating/deactivating the given constraint.

    As a workaround, always mark the constraints as installed, but for those constraints that need to be inactive on load, go to the identity inspector / user defined runtime attributes and add 'active' as a boolean set to false (unchecked)

    Found the solution here: https://stackoverflow.com/a/33079428/691868