title: Replace UITextViews text with attributed string
body: <p>I have a <code>UITextView</code> and when the user is entering text into it, I want to format the text on the fly. Something like syntax highlighting...</p>
  
  <p>For that I'd like to use <code>UITextView</code>...</p>
  
  <p>Everything works fine expect one problem: I take the text from the text view and make an <code>NSAttributedString</code> from of it. I make some edits to this attributed string and set it back as the <code>textView.attributedText</code>.</p>
  
  <p>This happens everytime the user types. So I have to remember the <code>selectedTextRange</code> before the edit to the <code>attributedText</code> and set it back afterwards so that the user can continue typing at the place he was typing before. The only problem is that once the text is long enough to require scrolling, the <code>UITextView</code> will now start scrolling to the top if I type slowly.</p>
  
  <p>Here is some sample code:</p>
  
  <pre><code>- (void)formatTextInTextView:(UITextView *)textView
  {
    NSRange selectedRange = textView.selectedRange;
    NSString *text = textView.text;
  
    // This will give me an attributedString with the base text-style
    NSMutableAttributedString *attributedString = [self attributedStringFromString:text];
  
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&amp;error];
    NSArray *matches = [regex matchesInString:text
                                      options:0
                                        range:NSMakeRange(0, text.length)];
  
    for (NSTextCheckingResult *match in matches)
    {
      NSRange matchRange = [match rangeAtIndex:0];
      [attributedString addAttribute:NSForegroundColorAttributeName
                               value:[UIColor redColor]
                               range:matchRange];
    }
  
    textView.attributedText = attributedString;
    textView.selectedRange = selectedRange;
  }
  </code></pre>
  
  <p>Is there any solution without using CoreText directly? I like the <code>UITextView</code>s ability to select text and so on....</p>