abentotoro
abentotoro

Reputation: 325

iOS: How to add constraints for textfield in a table cell in code

I use Xcode5, iOS SDK 7.

I create a UITextField in a table cell in code, not in storyboard. I want the width of textField should always be same as the width of the cell, but I don't know how achieve it.

I know I should use NSLayoutConstraint, but I can't find a tutorial, and I have tried in my way, they all can't work....

Could anyone help me out? Thanks a lot!

The snippet of code:

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: cellIdentifier];

UITextField *textField = [[UITextField alloc]initWithFrame: cell.contentView.frame];
[cell addSubview:textField];

Upvotes: 1

Views: 2500

Answers (2)

abentotoro
abentotoro

Reputation: 325

Thanks to @Renish Dadhaniya 's answer, I figured it out:

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: cellIdentifier];

UITextField *textField = [[UITextField alloc]initWithFrame: cell.contentView.frame];
[cell addSubview:textField];

[textField setTranslatesAutoresizingMaskIntoConstraints:NO];

NSLayoutConstraint *textLeftConstraint = [NSLayoutConstraint constraintWithItem: textField attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.f];

NSLayoutConstraint *textRightConstraint = [NSLayoutConstraint constraintWithItem: textField attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:0.f];

[cell addConstraint:textLeftConstraint];
[cell addConstraint:textRightConstraint];

It works well!!

Upvotes: 2

Related Questions