Reputation: 325
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
Reputation: 10752
Below link for Autolayout.
1. Auto layout in iOS6 adding constraints through code
2. iOS auto layouts
3. Auto layout for iOS revisited
4. Beginning auto layout tutorial in iOS7
Upvotes: 1
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