Get UILabels size strictly based on its text and font

suggest change

NSString provides boundingRectWithSize, which can predict the CGSize of a UILabel from its text and font without creating the label. The font attribute must be a UIFont. The Swift calls below are Swift 2. The second sample used lblDesc, which is not the outlet; it uses lblDescription.

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 the label and a height-constraint outlet. Add the code below where you assign text to the label.

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

let maxWidth = UIScreen.mainScreen().bounds.size.width - 40
let sizeOfLabel = self.lblDescription.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.max))
self.lblDescriptionHeightConstraint.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