如何动态修改约束NSLayoutConstraint

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何动态修改约束NSLayoutConstraint相关的知识,希望对你有一定的参考价值。

Constraint也可以像控件一样做Outlet链接的,你在你的ViewController的头文件里定义一个:
@property (weak) IBOutlet NSLayoutConstraint *constraint;
然后在SB里选中你的ViewController对象,Ctrl+鼠标拖动到Document Outlet里面的对应Constraint就可以了。和给Textfield做链接一样一样的。
参考技术A 看一下NSLayoutConstraint的api 只有constant可以修改,其它都是只读的。要改其它的属性,就得移除这个constranit再加入一个新的。然后update一下。想修改,肯定得先找到吧。添加的时候,记录一下,第二就是 循环查找。ios7 上 没有标识字段,查找要判断多个相等,才能找到。本回答被提问者采纳

以编程方式向UITextField添加约束

我正在学习自动布局而不使用StoryBoard。我给出了尾随,前导,顶部和底部的四个约束。

码:

UITextField *searchBarTF=[[UITextField alloc]init];  
[searchBarTF setText:@"is it coming?"];
[views addSubview:searchBarTF];

[views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeLeading multiplier:1.0 constant:30]];

[views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeTrailing   relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:30]];

[views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeTop    relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeTop multiplier:1.0 constant:30]];

[views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeBottom multiplier:1.0 constant:230]];

TextField未出现在屏幕上。

错误:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
答案

你只是忘了这段代码:

[searchBarTF setTranslatesAutoresizingMaskIntoConstraints:NO];

默认情况下,这是True。因此,您的约束与自动调整约束相冲突。

上面的行将禁用文本字段的自动调整大小,它将应用您定义的约束。

以上是关于如何动态修改约束NSLayoutConstraint的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式向UITextField添加约束

如何动态修改日历高度?

Android ConstraintLayout ConstraintSet动态布局

修改底层布局约束时 UICollectionViewCell 子类大小不正确

在 iOS 上使用自动布局如何指定视图应占用尽可能多的空间?

iOS开发之Masonry框架源码解析