【问题标题】:iOS: How to add constraints for textfield in a table cell in codeiOS:如何在代码中的表格单元格中为文本字段添加约束
【发布时间】:2014-01-10 10:09:56
【问题描述】:

我使用 Xcode5,iOS SDK 7。

我在代码中的表格单元格中创建UITextField,而不是在情节提要中。我希望textField的宽度应该总是和单元格的宽度一样,但是不知道怎么实现的。

我知道我应该使用NSLayoutConstraint,但是我找不到教程,我尝试过我的方式,它们都无法工作....

谁能帮帮我?非常感谢!

代码的sn-p:

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

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

【问题讨论】:

    标签: ios uitableview uitextfield nslayoutconstraint


    【解决方案1】:

    感谢@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];
    

    效果很好!!

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      相关资源
      最近更新 更多