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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any iOS Question?