oopsi
oopsi

Reputation: 2039

How to edit constraint in code

I have a web page that start with a width constrain of 100.

When the user click a button i want to change the constrain to : 200.

I tried this:

NSLayoutConstraint *constrain = [NSLayoutConstraint
                                 constraintWithItem:self.webPage
                                 attribute:NSLayoutAttributeWidth
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:self.webPage
                                 attribute:NSLayoutAttributeWidth
                                 multiplier:1
                                 constant:100];




[self.webPage addConstraint:constrain];

But this throws out this exception : "Unable to simultaneously satisfy constraints."

Any ideas?

Upvotes: 11

Views: 14315

Answers (2)

Matthias Bauch
Matthias Bauch

Reputation: 90117

You have two options.

  1. Get a reference to the original constraint and change the constant part to 200
  2. Get a reference to the original constraint and remove it from the view, and add the new constraint

I would go for the first option. To get a reference add a @property for the constraint to your viewController and assign it when you create it.

If you are creating the constraint in a xib or storyboard connect the constraint with a IBOutlet connection to your code, similar to what you do when you connect a UILabel.

You can then easily adjust the constant part of the constraint.


Also you constraint should probably be more along these lines:

NSLayoutConstraint *constraint = [NSLayoutConstraint
                                 constraintWithItem:self.webPage
                                 attribute:NSLayoutAttributeWidth
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute
                                 multiplier:1
                                 constant:100];

Upvotes: 27

BooRanger
BooRanger

Reputation: 1526

if you want to set the width don't have a toItem: set.

_myConstrain = [NSLayoutConstraint
                             constraintWithItem:self.webPage
                             attribute:NSLayoutAttributeWidth
                             relatedBy:NSLayoutRelationEqual
                             toItem:nil
                             attribute:NSLayoutAttributeNotAnAttribute
                             multiplier:1
                             constant:100];

// add to superview! not to self.webPage 
[self.view addConstraint:_myConstrain];

When you want to change it later:

_myConstrain.constant = 200.0f; 
[self.view layoutIfNeeded]; // you may be able to call this on self.webPage

Upvotes: 9

Related Questions