Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
oopsi Avatar asked Sep 19 '13 14:09

oopsi


Video Answer


1 Answers

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];
like image 138
Matthias Bauch Avatar answered Nov 12 '22 07:11

Matthias Bauch