Code Code - 2 years ago 300
Swift Question

Wrong text height when text contains emoji

Following the official docs, I created this function to calculate text height.

func calculateTextHeight(myString: String, myWidth: CGFloat, myFont: UIFont) -> CGFloat {
let textStorage = NSTextStorage(string: myString)
let textContainer = NSTextContainer(size: CGSize(width: myWidth, height: CGFloat.max))
let layoutManager = NSLayoutManager()


textStorage.addAttribute(NSFontAttributeName, value: myFont, range: NSMakeRange(0, textStorage.length))
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = .ByWordWrapping

return layoutManager.usedRectForTextContainer(textContainer).size.height

But the calculated height is wrong when the text contains an emoji.

var s = "ABCDE 12345"
print(calculateTextHeight(s, myWidth: 500, myFont: UIFont.systemFontOfSize(14)))
// prints 16.7 (correct)

s = "ABCDE 12345

Answer Source

I used an alternate method to calculate text height. This works with emojis.

static func calculateStringHeight(str: String, maxWidth: CGFloat, font: UIFont) -> CGFloat {
    return str.boundingRectWithSize(CGSizeMake(maxWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil).height
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download