Last active
October 8, 2017 12:19
-
-
Save alfian0/34f4bc90002f34e4a614264f122794dc to your computer and use it in GitHub Desktop.
Swift UILable Utils - Get UILabel Heigth based string length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
simple way