I have a problem with NSAttributedString in a UITextField ,
So, I want the usernames in the text box to be blue. This code works for this purpose, but the problem is that when the user hit the text box before the username, the rest of the text will turn blue.
Example:
(suppose the character "|" is the actual input position)
Hi, this Franckis how are you? |
hello it Franck|
hello it Franck, how are you?|
Here is my code for reference.
int i = 0;
for (NSString * username in _totalUsername){
NSRange mentionHere = [editText rangeOfString:_totalMentionTyped[i]];
if(mentionHere.location != NSNotFound){
[attributedString replaceCharactersInRange:[editText rangeOfString:_totalMentionTyped[i]] withString:username];
}
NSRange range = [[attributedString string] rangeOfString:username];
while(range.location != NSNotFound){
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
[attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15.0] range:range];
range = [[attributedString string] rangeOfString:username options:0 range:NSMakeRange(range.location + 1, [[attributedString string] length] - range.location - 1)];
}
i++;
}
self.commentTextField.attributedText = attributedString;
source
share