Search code examples
iosswiftheightuilabelframe

Adjust UILabel height to text


I have some labels which I want to adjust their height to the text, this is the code I wrote for this now

func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.font = font
    label.text = text

    label.sizeToFit()
    return label.frame.height
}

EDIT:

The issue was not in this piece of code, so my fix is in the question itself. It might still be useful for others!


Solution

  • I've just put this in a playground and it works for me.

    Updated for Swift 4.0

    import UIKit
    
     func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = text
    
        label.sizeToFit()
        return label.frame.height
    }
    
    let font = UIFont(name: "Helvetica", size: 20.0)
    
    var height = heightForView("This is just a load of text", font: font, width: 100.0)
    

    Swift 3:

    func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
        let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = text
        label.sizeToFit()
    
        return label.frame.height
    }
    

    enter image description here