我正在使用NSMutableAttributedString在用户输入时更改UITextView中的文本。当用户键入“#HELLO#”或“#TEST#”或“#test#”时,这些字符串应为红色(仅作为示例)。
- (void)textViewDidChange:(UITextView *)textView
{
NSString *textViewText = textView.text;
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:textViewText];
NSString *space = @" ";
NSArray *words =[textView.text componentsSeparatedByString:space];
for (NSString *word in words) {
if ([word isEqualToString:@"#HELLO#"] || [word isEqualToString:@"#TEST#"] || [word isEqualToString:@"#test#"]) {
NSRange range=[textView.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
else{
NSRange range=[textView.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
}
}
[string addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"HelveticaNeue-Light" size:20.0]
range:NSMakeRange(0, [textView.text length])];
[textView setAttributedText:string];
}
几乎每个单词都适用,除了'in'。当我输入时,'in'是黑色而不是白色([UIColor whiteColor]
)。如果我输入“t”,“#test#”中的“t”将变为白色。
我真的很困惑,有人可以帮帮我吗?我认为else
部分应该抓住这些字符串。感谢。
答案 0 :(得分:0)
我尝试了你的代码。我想问题是你设置的范围。因为它始终是一个单词,所以它设置该特定单词第一次出现的颜色属性。无论是#HELLO#还是#HELLO#。尝试按空格重复键入特定字符串,您将始终获得相同的输出。我在您的代码中进行了一些更改,您可以在下面看到它。尝试一下。
- (void)textViewDidChange:(UITextView *)textView
{
NSString *textViewText = textView.text;
NSLog(@"Text view Text %@" , textViewText );
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:textViewText];
NSString *space = @" ";
NSArray *words =[textView.text componentsSeparatedByString:space];
for(NSString *word in words){
NSLog(@"WORD %@" , word);
if ([word isEqualToString:@"#HELLO#"] || [word isEqualToString:@"#TEST#"] || [word isEqualToString:@"#test#"]) {
NSRange range = NSMakeRange(0, string.length);
while(range.location != NSNotFound)
{
range = [[string string] rangeOfString:word options:0 range:range];
if(range.location != NSNotFound)
{
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range.location, word.length)];
range = NSMakeRange(range.location + range.length, string.length - (range.location + range.length));
}
}
}
else{
NSRange range = NSMakeRange(0,string.length);
while(range.location != NSNotFound)
{
range = [[string string] rangeOfString:word options:0 range:range];
if(range.location != NSNotFound)
{
[string addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
range = NSMakeRange(range.location + range.length, string.length - (range.location + range.length));
}
}
}
}
[string addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"HelveticaNeue-Light" size:20.0]
range:NSMakeRange(0, [textView.text length])];
[textView setAttributedText:string];
}