如何在代码中编辑约束 [英] How to edit constraint in code

查看:125
本文介绍了如何在代码中编辑约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

我尝试过:

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




[self.webPage addConstraint:constrain];

但是这会抛出这个异常:
无法同时满足约束。 p>

任何想法?

解决方案


  1. 获取对原始约束的引用,将常量部分更改为200

  2. 获取对原始约束的引用并将其从视图中删除,然后添加新约束

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



如果您在xib或故事板中创建约束,将带有IBOutlet连接的约束连接到您的代码,类似于您在连接UILabel时所做的操作。



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






此外,您的约束应该更符合以下条件:

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


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?

解决方案

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 *constrain = [NSLayoutConstraint
                                 constraintWithItem:self.webPage
                                 attribute:NSLayoutAttributeWidth
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute
                                 multiplier:1
                                 constant:100];

这篇关于如何在代码中编辑约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆