Incorrect text height when text contains emoji

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

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() layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) textStorage.addAttribute(NSFontAttributeName, value: myFont, range: NSMakeRange(0, textStorage.length)) textContainer.lineFragmentPadding = 0 textContainer.lineBreakMode = .ByWordWrapping layoutManager.glyphRangeForTextContainer(textContainer) return layoutManager.usedRectForTextContainer(textContainer).size.height } 

But the calculated height is incorrect when the text contains emoji.

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

This is mistake? How can i fix this?

+5
source share
2 answers

I used an alternative method to calculate the height of the text. 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 } 
0
source

I do not think this is a mistake. Emoji takes up more space to display.

I believe that this will only matter if the amount of emoji in your text is too large. If you try the code below, I think the result will be the same.

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

If you want to eliminate emojis, you can remove them from the source text before calculating the height. In this case, you need to scan the source text, replacing all emojis with another character, and then call the calculation of the height.

-1
source

Source: https://habr.com/ru/post/1242939/


All Articles