如何在代码中编辑约束



我有一个以宽度约束 100 开头的网页。

当用户单击按钮时,我想将约束更改为:200。

我试过这个:

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


[self.webPage addConstraint:constrain];

但这抛出了这个异常:"无法同时满足约束。"

有什么想法吗?

您有两个选择。

  1. 获取对原始约束的引用并将constant部分更改为 200
  2. 获取对原始约束的引用并将其从视图中删除,然后添加新约束

我会选择第一个选项。要获取引用,请将约束的@property添加到 viewController 中,并在创建时分配它。

如果要在 xib 或情节提要中创建约束,请将约束与代码的 IBOutlet 连接连接,类似于连接 UILabel 时执行的操作。

然后,您可以轻松调整约束的常量部分。


此外,您的约束可能应该更符合以下几行:

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

如果要设置宽度,请不要设置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];

当您以后要更改它时:

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

最新更新