Arian Sharifian
Arian Sharifian

Reputation: 1295

Replace part of UITextView's attributed text

I'm trying to create a text view in my app. It simply highlights the syntax and displays the highlighted text in a UITextView via AttributedText. Here's the code:

NSMutableString *ms = [[NSMutableString alloc] initWithString:self.text];
[ms replaceCharactersInRange:range withString:text];
self.attributedText = [syntaxHighlighter highlight:ms inRange:[self visibleRangeOfText]];
[self setSelectedRange:NSMakeRange(range.location + text.length, 0)];

The problem is for large texts, it has to replace the whole text in 3rd line. Is there a way to just replace a part of text without replacing the whole content?

Upvotes: 2

Views: 742

Answers (1)

Tony
Tony

Reputation: 4591

UITextView implements UITextInput protocol.

If you want to replace a part of text without replacing the whole content, you can use method:

- (void)replaceRange:(UITextRange *)range withText:(NSString *)text;

But in some special case (when calling from other class), this method is not effective. I dont know why so I used:

double delayInSeconds = 0.2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     //call method to change text of textView here...
});

Good luck!

Upvotes: 2

Related Questions