LoadData LoadData - 1 month ago 27
iOS Question

Resize UITableViewCell Height based on UILabel Content

I've been looking into this for over a day now, and I can honestly say I am completely stumped by why this is not working as I would expect it to.

I'm trying to have a UITableViewCell expand when selected to the correct size based on the UILabel within it. I have used the following code to determine the required size for the UILabel:

extension UILabel {

func requiredHeight() -> CGFloat{

let label:UILabel = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.max))
label.text = self.text
label.numberOfLines = 0
label.font = self.font

label.sizeToFit()


print("Final Size - \(label.frame.height)")
return label.frame.height + 10
}
}


My issue is, despite this size - when the Cell is resized within the 'heightForRowAtIndexPath' method - it is still not the correct size and the string is being truncated, this can be seen in the below image.

enter image description here

To note - I gather the required size of the cell as soon as the view has loaded and text has been populated into the UILabel.

requiredHeight = overviewLabel.requiredHeight()
if requiredHeight > overviewCell.frame.height {
expander.hidden = false
} else {
expander.hidden = true
}


Any advice on how this could be fixed will be greatly appreciated.

Answer

Try this snippet. Just provide exact name of the font and size

Swift 3.x

func requiredHeight() -> CGFloat{
    let font = UIFont(name: "Helvetica", size: 16.0)
    let label:UILabel = UILabel(frame: CGRect(x:0, y:0, width:200, height:CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = self.text
    label.sizeToFit()
    return label.frame.height + //Add some space as a part of your bottom and top constraint
}

Swift 2.2

func requiredHeight() -> CGFloat{
    let font = UIFont(name: "Helvetica", size: 16.0)
    let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.font = font
    label.text = self.text
    label.sizeToFit()
    return label.frame.height + //Add some space as a part of your bottom and top constraint
}

Suppose your label has top and bottom constraint as 5 and 5 respectively, them make the return statement as

return label.frame.height + 10

NOTE:- Width should be the width you want of the label. It should be according to your UITableView or UIView