Get UILabels size strictly based on its text and font

suggest change

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

Objective-C

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

Swift

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

Swift

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents