ios - How to stop cursor changing position when I setAttributedText in UITextView delegate method textViewDidChange -


the following code changes "test" in textview's string red color has effect of moving cursor end of text block when textviewdidchange called (aka when text editing made annoying).

how can prevent cursor moving when setattributedtext in textviewdidchange?

- (void)textviewdidchange:(uitextview *)textview {      nsstring* currentstring = self.textview.text;     nsmutableattributedstring* string = [[nsmutableattributedstring alloc]initwithstring:currentstring];     nsarray *words=[currentstring componentsseparatedbystring:@" "];      (nsstring *word in words) {         if ([word isequaltostring:@"test"]) {             // change color             nsrange range=[currentstring rangeofstring:word];             [string addattribute:nsforegroundcolorattributename value:[uicolor redcolor] range:range];         }     }      // assign new color textview's text     [self.textview setattributedtext:string]; } 

simply save , restore selected range:

nsrange selectedrange = self.textview.selectedrange; self.textview.attributedtext = string; self.textview.selectedrange = selectedrange; 

Comments

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -