添加子视图后自动调整单元格

时间:2017-07-04 12:06:50

标签: ios uitableview swift3

我正在创建一个包含自定义单元格的表格 - 在表格的最后一个单元格中,我需要更改UItextField的{​​{1}} - 我在UILabel中执行此代码:

cellForRowAt

我正在检查单元格是否是正确的单元格,添加标签并隐藏UITextField,这一切都有效。但是,当我运行程序时,标签会调整大小以适应线条,但单元格不会调整大小以适合标签。 我需要更改以使用添加的标签重新调整此单元格的大小,我已使用case "Notes": if viewing == true { for subview in cell.contentView.subviews { if subview.description.contains("UITextField") { let newField = UILabel() cell.contentView.addSubview(newField) newField.frame = cell.infoField.frame newField.text = profileToShow.notes newField.font = cell.infoField.font newField.addConstraints(cell.infoField.constraints) newField.lineBreakMode = NSLineBreakMode.byWordWrapping for constraint in cell.infoField.constraints { cell.infoField.removeConstraint(constraint) } cell.infoField.isHidden = true newField.numberOfLines = 0 } } } break

1 个答案:

答案 0 :(得分:1)

尝试更改cellForRowAtIndexPath中的顺序,并在添加约束后添加layoutIfNeeded

case "Notes":
    if viewing == true {
        for subview in cell.contentView.subviews {
            if subview.description.contains("UITextField") {
                let newField = UILabel()
                 cell.contentView.addSubview(newField)

                 newField.frame = cell.infoField.frame
                 newField.numberOfLines = 0
                 newField.font = cell.infoField.font
                 newField.addConstraints(cell.infoField.constraints)
                 newField.lineBreakMode = NSLineBreakMode.byWordWrapping

                 for constraint in cell.infoField.constraints {
                     cell.infoField.removeConstraint(constraint)
                 }

                 cell.infoField.isHidden = true
                 newField.text = profileToShow.notes
                 cell.layoutIfNeeded()
             }
         }
     }
 break