以编程方式向 UITextField 添加约束

Adding constraints to UITextField programmatically

我在不使用 StoryBoard 的情况下学习自动布局。我给出了trailing, leading, top and bottom 四个约束。

代码:

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。所以你的约束与 Autoresizing 约束冲突。

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