Code Code - 9 months ago 175
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


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