ZiEiTiA
ZiEiTiA

Reputation: 275

Autoresize cell after adding subview

I am creating a table with custom cells - in the last cell in the table I need to change the UItextField for a UILabel - which I am doing with this code in cellForRowAt:

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

I am checking to see if the cell is the correct cell, which it is, adding the label and hiding the UITextField, which all works. However when I run the program the label is resizing to fit the lines, but the cell is not resizing to fit the label. What do I need to change to make this cell re-size with the added label, i am using the UITableViewAutomaticDimension already.

Upvotes: 1

Views: 162

Answers (1)

Aravind A R
Aravind A R

Reputation: 2714

Try changing the order in the cellForRowAtIndexPath and add layoutIfNeeded after adding constraints

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

Upvotes: 1

Related Questions