Note that there are some explanatory texts on larger screens.

plurals
  1. POUITextView attributedText and syntax highlighting
    text
    copied!<h1>Background</h1> <p>So, with iOS 6 an UITextView can take an attributedString, which could be useful for Syntax highlighting.</p> <p>I'm doing some regex patterns in <code>-textView:shouldChangeTextInRange:replacementText:</code> and oftentimes I need to change the color of a word already typed. I see no other options than resetting the attributedText, which takes time.</p> <pre><code>- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { //A context will allow us to not call -attributedText on the textView, which is slow. //Keep context up to date [self.context replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc] initWithString:text attributes:self.textView.typingAttributes]]; // […] self.textView.scrollEnabled = FALSE; [self.context setAttributes:self.defaultStyle range:NSMakeRange(0, self.context.length)]; [self refresh]; //Runs regex-patterns in the context   textView.attributedText = self.context; self.textView.selectedRange = NSMakeRange(range.location + text.length, 0); self.textView.scrollEnabled = TRUE; return FALSE; } </code></pre> <p>This runs okayish on the simulator, but on an iPad 3 each <code>-setAttributedText</code> takes a few hundreds of milliseconds.</p> <p>I filed a bug to Apple, with the request of being able to mutate the attributedText. It got marked as a duplicate, so I cannot see what they're saying about this.</p> <h1>The question</h1> <p><strong>The more specific question:</strong> How can I change the color of certain ranges in a UITextView, with a large multicolored text, with good enough performance to do it in every <code>shouldReplaceText...</code>?</p> <p><strong>The more broad question:</strong> How do you do syntax highlighting with a UITextView in iOS 6?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload