How to edit constraint in code

放肆的年华 提交于 2019-12-04 17:49:28

问题


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?


回答1:


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];



回答2:


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


来源:https://stackoverflow.com/questions/18897353/how-to-edit-constraint-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!