我使用的是Xcode5,iOS SDK 7。
我在代码中的表格单元格中创建UITextField
,而不是在故事板中。我希望textField的宽度应该始终与单元格的宽度相同,但我不知道如何实现它。
我知道我应该使用NSLayoutConstraint
,但我找不到教程,而且我已经尝试过了,他们都无法工作......
有人可以帮帮我吗?非常感谢!
代码片段:
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: cellIdentifier];
UITextField *textField = [[UITextField alloc]initWithFrame: cell.contentView.frame];
[cell addSubview:textField];
答案 0 :(得分:2)
感谢@Renish Dadhaniya的回答,我明白了:
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];
效果很好!!
答案 1 :(得分:1)