簡體   English   中英

以編程方式向UITextField添加約束

[英]Adding constraints to UITextField programmatically

我正在學習自動布局而不使用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 因此,您的約束與自動調整大小約束沖突。

上面的行將禁用自動調整文本字段的大小,並將應用您定義的約束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM