简体   繁体   中英

Adding constraints to UITextField programmatically

I am learning auto layout without using StoryBoard. I have given four constraints of trailing, leading, top and bottom.

Code:

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 is not appearing on screen.

Error:

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

You just forget this little piece of code:.

[searchBarTF setTranslatesAutoresizingMaskIntoConstraints:NO];

By default, this is True . So your constraints are conflicting with Autoresizing constraints.

The above line will disable auto resizing of your text field and it will apply your defined constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM