Skip to content

Instantly share code, notes, and snippets.

@alfian0
Last active October 8, 2017 12:19
Show Gist options
  • Save alfian0/34f4bc90002f34e4a614264f122794dc to your computer and use it in GitHub Desktop.
Save alfian0/34f4bc90002f34e4a614264f122794dc to your computer and use it in GitHub Desktop.
Swift UILable Utils - Get UILabel Heigth based string length
extension UILabel {
func getEstimatedHeight(width: CGFloat) -> CGFloat {
guard let text = self.text else { return CGFloat.min }
var maxHeight = CGFloat.max
if (self.numberOfLines > 0) {
maxHeight = (ceil(self.font.lineHeight) * CGFloat(self.numberOfLines))
}
let maxSize = CGSizeMake(width, maxHeight)
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
let estimatedSize = NSString(string: text).boundingRectWithSize(maxSize, options: options, attributes: [NSFontAttributeName: self.font], context: nil)
return estimatedSize.height
}
func width(font: UIFont) -> CGFloat {
return (self as NSString).size(attributes: [NSFontAttributeName: font]).width
}
}
@alfian0
Copy link
Author

alfian0 commented Oct 8, 2017

simple way

self.subtitleLabel.sizeThatFits(CGSize(width: width - 32, height: CGFloat.greatestFiniteMagnitude)).height

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment