3

I have an issue with a NSAttributedString in a UITextField,

So what I want is that the usernames in the the textfield are in color blue. This code is working for this purpose but the problem is, when user hit back in the textfield until a username, the rest of the text become blue.

example:

(let's suppose the "|" character is the actual typing position)

hello this is Franck, how are you?|

hello this is Franck|

hello this is Franck, how are you?|

Here is some of 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;
Community
  • 1
  • 1
Seylar
  • 151
  • 1
  • 1
  • 5
  • 1
    Get each word by NSArray *words = [self.text.text componentsSeparatedByString:@" "]; using array and compare each word with username, is it match then change color otherwise not :) – iPatel Feb 05 '14 at 05:13

1 Answers1

0

You can accomplish this by implementing the textField:shouldChangeCharactersInRange:replacementString: method and setting the attributed text on the text field:

- (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;
}