title: Aligning glyphs to the top of a UITextView after sizeToFit
body: <p>The app I'm working on supports hundreds of different fonts. Some of these fonts, particularly the script fonts, have significant ascenders and descenders. When <code>sizeToFit()</code> is called on a <code>UITextView</code> with some of these fonts, I end up with significant top and bottom padding (the image on the left). The goal is to end up with the image on the right, such that the tallest glyph is aligned flush with the top of the text view's bounding box.</p>
  
  <p><a href="https://i.stack.imgur.com/3FodV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3FodV.png" alt="UITextView Layout Examples"></a></p>
  
  <p>Here's the log for the image above:</p>
  
  <pre><code>Point Size: 59.0
  Ascender:  70.21
  Descender:  -33.158
  Line Height:  103.368
  Leading: 1.416
  TextView Height: 105.0
  </code></pre>
  
  <p>My first thought was to look at the height of each glyph in the first line of text, and then calculate the offset between the top of the container and the top of the tallest glyph. Then I could use <code>textContainerInset</code> to adjust the top margin accordingly. </p>
  
  <p>I tried something like this in my <code>UITextView</code> subclass:</p>
  
  <pre class="lang-swift prettyprint-override"><code>for location in 0 ..&lt; lastGlyphIndexInFirstLine {
      let glphyRect = self.layoutManager.boundingRect(forGlyphRange: NSRange(location: location, length: 1), in: self.textContainer)
      print(glphyRect.size.height) // prints 104.78399999999999 for each glyph
  }
  </code></pre>
  
  <p>Unfortunately, this doesn't work because <code>boundRect(forGlyphRange:in:)</code> doesn't appear to return the rect of the glyph itself (I'm guessing this is always the same value because it's returning the height of the line fragment?).</p>
  
  <p>Is this the simplest way to solve this problem? If it is, how can I calculate the distance between the top of the text view and the top of the tallest glyph in the first line of text?</p>