user2876886
user2876886

Reputation:

Activating and Deactivating Constraints Not Updating View Frame

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:

  1. Label bottom to Button top equals 0. (Constraint1)
  2. Label bottom to Button top greater than or equal to 0 (Constraint3)
  3. Button Height (Constraint3)

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.

enter image description here

If the Button is not needed, Constraint1 gets installed and Constraint3 gets set to 0.

enter image description here

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:

enter image description here

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

Answers (1)

Shehata Gamal
Shehata Gamal

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

Related Questions