用属性字符串替换UITextViews文本

Geo*_*org 14 uitextview nsattributedstring core-text ios

我有一个UITextView,当用户输入文本时,我想动态格式化文本.语法高亮......

为此,我想用UITextView...

一切正常,期待一个问题:我从文本视图中获取文本并从中NSAttributedString获取.我对这个属性字符串进行了一些编辑,并将其设置为textView.attributedText.

每次用户输入时都会发生这种情况.所以我必须记住selectedTextRange编辑之前的attributedText事情,然后将其设置回来,以便用户可以继续在他之前输入的地方打字.唯一的问题是,一旦文本足够长就需要滚动,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;
}
Run Code Online (Sandbox Code Playgroud)

有没有直接使用CoreText的解决方案?我喜欢UITextView选择文字的能力等等....

Ser*_*nov 37

我不确定这是正确的解决方案,但它确实有效.
只需在格式化文本之前禁用滚动,并在格式化后启用它

- (void)formatTextInTextView:(UITextView *)textView
{
    textView.scrollEnabled = NO;
    NSRange selectedRange = textView.selectedRange;
    NSString *text = textView.text;

    // This will give me an attributedString with the base text-style
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: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;
    textView.scrollEnabled = YES;
}
Run Code Online (Sandbox Code Playgroud)