How to get real height of HTML text attribute

I have a slightly complicated scenario here.

I have a web server that sends JSON data back to my application, and one of the pieces of data is HTML text, for example json:

... { id: 3, name: "Content Title", description: "<p>This is a paragraph block</p><p>This is another paragraph</p>", } 

As you know, text with an HTML attribute adds another level of complexity as HTML tags change the height of the actual text.

So the line is like this:

 "Hello World" 

there can only be 10 pixels tall as a normal string, but if formatted as follows:

 "<h1>Hello World</h1>" 

Real height can be above 10 pixels.

I want to know how I can calculate that real height ?

This is how I calculated the UILabel heights with attribute strings, but it only seemed to give me a height that works perfectly with text pixels, not the block size of an HTML element:

 -(CGFloat)dynamicHeightForHTMLAttributedString:(NSString *)dataString UsingWidth:(CGFloat)width AndFont:(UIFont *)font { NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; NSMutableAttributedString *htmlString = [[NSMutableAttributedString alloc] initWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil]; [htmlString addAttributes:attrsDictionary range:NSMakeRange(0, htmlString.length)]; CGRect rect = [htmlString boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil]; CGSize size = rect.size; return ceilf(size.height); } 

Is this right to do?

+6
source share

All Articles