我有一个UITextView
,当用户输入文本时,我想即时对文本进行格式化。就像语法高亮一样...
为此,我想使用UITextView
...
除了一个问题外,一切都运行良好:我从文本视图中获取文本,并从中创建一个NSAttributedString
。我对此属性字符串进行了一些编辑,并将其设置回textView.attributedText
。
这发生在用户每次输入时。因此,我必须在编辑attributedText
之前记住所选的selectedTextRange
,并在之后将其设置回去,以便用户可以在之前输入的位置继续输入。唯一的问题是,一旦文本足够长需要滚动,如果我打字速度较慢,UITextView
现在会开始向顶部滚动。
下面是一些示例代码:
- (void)formatTextInTextView:(UITextView *)textView
{
NSRange selectedRange = textView.selectedRange;
NSString *text = textView.text;
// This will give me an attributedString with the base text-style
NSMutableAttributedString *attributedString = [self attributedStringFromString:text];
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:text
options:0
range:NSMakeRange(0, text.length)];
for (NSTextCheckingResult *match in matches)
{
NSRange matchRange = [match rangeAtIndex:0];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:matchRange];
}
textView.attributedText = attributedString;
textView.selectedRange = selectedRange;
}
有没有不直接使用CoreText的解决方案?我喜欢UITextView
选择文本等功能....