Reputation:
I have a subview that contains a Label and a Button, however, the button is not always needed. If the Button is needed, the Label needs to be displayed at the top and the button at the bottom of the view. If the Button is not needed, the Label needs to be displayed in the middle of the view.
To accomplish this, I have three constraints I modify:
NOTE: The Label has a top constraint with the view set to 0 and the Button has a bottom constraint with the view set to 0. These go unchanged.
NOTE: All constraints are set to be installed and the button height is 42 at build time
If the Button is needed, Constraint1 gets uninstalled and Constraint3 gets set to 42.
If the Button is not needed, Constraint1 gets installed and Constraint3 gets set to 0.
As you can see, this works on the storyboard as expected. However, in code, the behavior is not reflected. If the button is needed, I try this:
constraint3.constant = 42
self.view.removeConstraint(constraint1)
self.view.updateConstraints
But instead of the expected result, I get a result as if the constraint was never removed:
I uninstall the constraint in storyboard and it looks correct, but when I uninstall the constraint in code, it doesn't... What is incorrect/missing from my code to get this working properly?
Upvotes: 2
Views: 2589
Reputation: 100533
change this
self.view.removeConstraint(constraint1)
to
parentView.removeConstraint(constraint1)
self.view.layoutIfNeeded()
This constraint need to be removed from the parent view of both the label and the button which contains that constraint
Upvotes: 1