我一直在使用TextKit
和NSTextStorage
对象UITextView
尝试获取某些字以动态格式化。NSTextStorage addAttribute仅适用于指定范围的字符
以下方法位于UITextView
的子类中,并在textDidChange
事件中执行。这样做的效果在于,它确实能够检测何时输入了“the”这个词,并且它确实将它变成红色,但是“the”之后的所有文字也是红色的。目标仅仅是“the”是红色的。
任何想法我做错了什么?
- (void)highlight {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bthe\\b" options:0 error:nil];
NSArray *matches = [regex matchesInString:[self text] options:0 range:NSMakeRange(0, [self.text length])];
for (NSTextCheckingResult *match in matches) {
[self.textStorage beginEditing];
[self.textStorage addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:match.range];
[self.textStorage endEditing];
}
}
'match.range'的值是否正确? –
是的,范围已被证实是正确的。 –
尝试将所有匹配项设置为红色后,将文本视图的“typingAttributes”设置为“正常”属性(不管文本的属性是否为红色)。 –