Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to delete a NSLayoutConstraint

In my apps I'm working a lot with constraints, in most cases with animations as well. In certain circumstances I need to remove constraints and add new ones.

As I need to support iOS 7 as well, I'm not able to use the active property, which would else be the solution for me.

The way to remove constraints is to use the removeConstraint method on a UIView.

Is it possible to create a method like

constraint.remove()

so you don't have to know which view is taking care over the constraint?

like image 547
Antoine Avatar asked May 07 '15 13:05

Antoine


2 Answers

What I do is create arrays of the constraints that I wish to be able to add/remove and simply use the following:

@property NSMutableArray *newConstraints;

Fill up the newConstraints

iOS7 and iOS8:

[self.viewToChange addConstraints:self.newConstraints];
[self.viewToChange removeConstraints:self.newConstraints];

or iOS8 only, use the new mechanism

[NSLayoutConstraint activateConstraints:self.newConstraints];
[NSLayoutConstraint deactivateConstraints:self.newConstraints];

With this you can apply a set, remove the set and apply a new set.

You can also create the initial list from the storyboard set if you can identify which constraints are which.

like image 138
Rory McKinnel Avatar answered Oct 16 '22 09:10

Rory McKinnel


I've ended up using the method autoRemove provided by the PureLayout library: https://github.com/smileyborg/PureLayout

This method finds the commonSuperview using the firstItem or secondItem and removes the constraint from the correct view.

It resulted in this one liner:

containerTopConstraint.autoRemove()
like image 31
Antoine Avatar answered Oct 16 '22 07:10

Antoine