title: How to get real height of HTML attributed text
body: <p>I've got a bit of a complicated scenario here.</p>
  
  <p>I have a web server that sends JSON data back to my app and one of the piece of data is HTML text, example json:</p>
  
  <pre><code>...
  {
      id: 3,
      name: "Content Title",
      description: "&lt;p&gt;This is a paragraph block&lt;/p&gt;&lt;p&gt;This is another paragraph&lt;/p&gt;",
  }
  </code></pre>
  
  <p>As you may know, HTML attributed text adds another layer of complexity as the HTML tags modifies the height of the actual text.</p>
  
  <p>So a string like this:</p>
  
  <pre><code>"Hello World" 
  </code></pre>
  
  <p>might only be 10 pixel high as a normal string but if formatted like this:</p>
  
  <pre><code>"&lt;h1&gt;Hello World&lt;/h1&gt;"
  </code></pre>
  
  <p>The <b><em>real</em></b> height can potentially be higher than 10 pixel.</p>
  
  <p>What I want to know is how can I calculate that <b>real height</b>?</p>
  
  <p>This is how I've been calculating UILabel heights with attributed strings but it seems to only give me the height that fits the text pixels snugly rather than the actual HTML element block size:</p>
  
  <pre><code>-(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);
  }
  </code></pre>
  
  <p>Is this the right way to do it?</p>