Remplacer le texte UITextViews par une chaîne attribuée

J'ai un UITextView et lorsque l'utilisateur d'entrer du texte, je veux formater le texte à la volée. Quelque chose comme la coloration syntaxique...

Pour cela je voudrais utiliser UITextView...

Tout fonctionne bien s'attendre à un problème: je prends le texte de l'affichage de texte et de faire un NSAttributedString de de lui. J'ai apporter quelques modifications à cette attribué chaîne et la définir comme la textView.attributedText.

Cela se produit chaque fois que l'utilisateur tape. J'ai donc rappeler le selectedTextRange avant de le modifier pour le attributedText et le ramener par la suite, de sorte que l'utilisateur peut continuer à taper à l'endroit où il était avant de taper. Le seul problème est qu'une fois que le texte est assez long pour exiger le défilement, le UITextView va maintenant démarrer le défilement vers le haut si je tape lentement.

Voici un exemple de code:

- (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;
}

Est-il une solution sans l'aide de CoreText directement? J'aime la UITextViews possibilité de sélectionner du texte et ainsi de suite....

source d'informationauteur Georg