Is there a way to install and uninstall an Xcode interface builder constraint
programmatically?
Asked
Active
Viewed 1.4k times
26
-
take a look at open source project like mansory and pure layout on github. They are better and easier to code – Wingzero May 28 '15 at 01:40
-
Is there a way to get this question unclosed, as the meaning of the question is now obvious, and the correct answer is in a comment of an outdated answer? – timeSmith Oct 24 '19 at 04:44
1 Answers
22
Connect the IBOutlet for the NSLayoutConstraint by CTRL+click the constraint and drag it to the viewController (for ex. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint;
).
For removing the constraint:
[self.view removeConstraint:constraint]
for installing the constraint:
[self.view addConstraint:constraint]
-
So if a constraint starts out **un**installed, then by `addConstraint` will become installed? – Eric May 28 '15 at 00:49
-
@Eric "uninstall" is the wrong terminology here... *uninstall* is strictly in reference to the storyboard and has nothing to do with anything done programmatically at run time. – nhgrif May 28 '15 at 01:10
-
-
-
@nhgrif You're right, but when I add them both in storyboard, I get errors. – Eric May 28 '15 at 01:15
-
No one can help you with mysterious errors you're not mentioning... but most likely, you need to actually uncheck "installed" for one or the other. – nhgrif May 28 '15 at 01:16
-
-
@Eric You could tick the Placeholder remove at build time box of the constraint that you would install programmatically later on – A C May 28 '15 at 01:19
-
-
-
-
@Eric To active or deactivate `code`NSLayoutConstraint.deactivateConstraints(constraintsA) NSLayoutConstraint.activateConstraints(constraintsB)`code` – Ofcourse Jan 11 '16 at 14:15
-
37In iOS 8 there is an `active` property on constraint that corresponds to the "uninstalled" setting in XCode. Simply leave one constraint uninstalled in XCode with your alternate values and then switch between them by alternating their `active` states at run time. – Pat Niemeyer May 01 '16 at 14:37
-
22Just for the record! It might be dangerous to have a weak reference to the constraint if it will be added/removed in code! It might get released! – ullstrm May 10 '16 at 13:37
-
4This solution is deprecated. use NSLayoutConstraint's active property instead. – scord Jun 27 '18 at 00:04