我在 UITextField 中的 NSAttributedString 遇到问题,
所以我想要的是文本字段中的用户名是蓝色。
这段代码可用于此目的,但问题是,当用户在文本字段中回退直到输入用户名时,其余文本变为蓝色。
例:
(假设“|”字符是实际的键入位置)
你好,这是Franck
,你好吗?
您好,这是Franck
|
您好,这是Franck, how are you?
|
这是我的一些代码供参考。
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;
最佳答案
您可以通过实现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;
}