iOS Get UILabel's size strictly based on its text and font


NSString provides method boundingRectWithSize which can be used to predict the resulting CGSize of a UILabel based on its text and font without the need of creating a UILabel


[[text boundingRectWithSize:maxSize options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName: fontName} context:nil] size];


let nsText = text as NSString?
nsText?.boundingRectWithSize(maxSize, options: [.TruncatesLastVisibleLine, .UsesLineFragmentOrigin], attributes: [NSFontAttributeName: fontName], context: nil).size


Create Label and label Height constraint outlet. Add below code where you will asign text to label.

@IBOutlet var lblDescriptionHeightConstration: NSLayoutConstraint! 
@IBOutlet weak var lblDescription: UILabel!

let maxWidth = UIScreen.mainScreen().bounds.size.width - 40
let sizeOfLabel = self.lblDesc.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.max))
self.lblDescriptionHeightConstration.constant = sizeOfLabel.height

Note: "40" is the space of left and right side of screen.