Color attribute persisted by NSAttributedString in UITextField

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;
+3
source share
1 answer

, textField: shouldChangeCharactersInRange: replacementString: :

- (BOOL)textField:(UITextField *)textField
    shouldChangeCharactersInRange:(NSRange)range
    replacementString:(NSString *)string {
    NSString *replacementText = [[textField text] stringByReplacingCharactersInRange:range withString:string];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:replacementText];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont boldSystemFontOfSize:15.0]
                             range:NSMakeRange(0, [attributedString length])];
    NSRange rangeOfUsername = [[attributedString string] rangeOfString:@"josh"];
    if (rangeOfUsername.location != NSNotFound) {
      [attributedString addAttribute:NSForegroundColorAttributeName
                               value:[UIColor blueColor]
                               range:rangeOfUsername];
    }
    textField.attributedText = attributedString;
    return NO;
}
0

All Articles