title: NSLayoutManager boundingRectForGlyphRange off by some Points
body: <p>I want to "highlight" specific words in UITextView, not with a solid color (which would be possible via <code>NSAttributedString</code>), but rather with a gradient and maybe some other fancy effects. </p>
  
  <p>Hence, I decided it would be necessary to manually create a view and overlay (or underlay) it using the bounding rectangles of the given text.</p>
  
  <p>To my surprise this turned out to be pretty straightforward. Example is inside a UIViewController, <code>txtView</code> being a <code>UITextView</code> connected as <code>IBOutlet</code>:</p>
  
  <pre><code>override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
  
      // Converting to NSString as I need a NSRange for glphyRangeForCharacterRange
      // (a normal String in Swift returns a Range)
      let charRange = (txtView.text as NSString).rangeOfString("dolor sit er elit")
      assert(charRange.location != NSNotFound, "Character Range could not be found.")
  
      let glyphRange = txtView.layoutManager.glyphRangeForCharacterRange(charRange,
          actualCharacterRange: nil)
      let glyphContainer = txtView.layoutManager.textContainerForGlyphAtIndex(glyphRange.location, effectiveRange: nil)
      let glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
          inTextContainer: glyphContainer!)
  
      let highlightView = UIView(frame: glyphRect)
      highlightView.alpha = 0.3
      highlightView.backgroundColor = UIColor.redColor()
      txtView.addSubview(highlightView)
  }
  </code></pre>
  
  <p>Sadly, this leads to the overlain view (in red in the below screenshot), being off by a few points. </p>
  
  <p><img src="https://i.stack.imgur.com/DovsI.png" alt="Simulator Screenshot showing the red rectangle being off by a few points"></p>
  
  <p>It always seems to be off by the same amount. Which would mean I could probably hardcode, but that has never been a good idea. Tested this in Simulator with various devices and on an iPhone 6 with iOS 8.1.3.</p>
  
  <p>I also tried other variations (by creating my own NSTextContainer etc.) as inspired by <a href="https://stackoverflow.com/questions/19417776/how-do-i-locate-the-cgrect-for-a-substring-of-text-in-a-uilabel">the question on how to get a CGRect for a substring</a> and <a href="https://stackoverflow.com/questions/24970427/layoutmanager-boundingrectforglyphrangeintextcontainer-does-not-work-for-all-s">"boundingRectForGlyphRange does not always work for all strings"</a></p>
  
  <p>Any ideas (besides <a href="https://stackoverflow.com/questions/21666258/how-do-i-eliminate-leading-whitespace-when-computing-word-boundaries-using-bound">resorting to CoreText</a>)?</p>