title: Word wrap detecting in UITextView
body: <p>I am implementing a customized rich text editor by extending the UITextView. When user selects the text range and apples the 'highlighting' menu, the editor will draw a blue background for the selected text:</p>
  
  <pre><code>- (CGRect)getRectAtRangePos:(NSInteger)pos {
      UITextPosition *beginning = self.beginningOfDocument;
      UITextPosition *start = [self positionFromPosition:beginning offset:pos];
      CGRect rect = [self caretRectForPosition:start];
      return [self convertRect:rect fromView:self.textInputView];
  }
  
  
  - (void)drawRange:(NSRange)range {
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetRGBFillColor(context, 0x16/255.f, 0x38/255.f, 0xfc/255.f, 0.5);
      CGRect startRect = [self getRectAtRangePos:range.location];
      CGRect endRect = [self getRectAtRangePos:range.location + range.length];
  
      CGFloat padding = 1;
      CGFloat margin = 1;
  
      if (ABS(endRect.origin.y - startRect.origin.y) &lt; 5) {//They are in the same line
          CGRect wholeRect = CGRectMake(startRect.origin.x, startRect.origin.y + padding, endRect.origin.x - startRect.origin.x, startRect.size.height - 2 * padding);
          CGContextFillRect(context, wholeRect);
      }
      else {//The range occupies at least two lines
          CGRect firstRect = CGRectMake(startRect.origin.x, startRect.origin.y + padding, self.bounds.size.width - startRect.origin.x - margin, startRect.size.height - 2 * padding);
          CGContextFillRect(context, firstRect);
          CGFloat heightDiff = endRect.origin.y - (startRect.origin.y + startRect.size.height);
          if (heightDiff &gt; 5) {//The range occupies more than two lines
              CGRect secondRect = CGRectMake(margin, startRect.origin.y + startRect.size.height + padding, self.bounds.size.width - 2*margin, heightDiff - 2* padding);
              CGContextFillRect(context, secondRect);
          }
          CGRect thirdRect = CGRectMake(margin, endRect.origin.y + padding, endRect.origin.x, endRect.size.height - 2* padding);
          CGContextFillRect(context, thirdRect);
      }
  }
  </code></pre>
  
  <p>When the selected text contains a long word which caused the word wrap, the blue background looks ugly.</p>
  
  <p><img src="https://i.stack.imgur.com/9luq6.png" alt="enter image description here"></p>
  
  <p>Is there a way to detect the position where the word wrap? Thanks!</p>