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
Post a Comment