How to edit constraint in code

主宰稳场 提交于 2019-12-03 11:37:05
Matthias Bauch

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

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