Modifier les attributs des sous-chaînes dans un NSAttributedString

Cette question peut être un doublon de cette une. Mais les réponses ne fonctionnent pas pour moi et je veux être plus précis.

J'ai un NSStringmais j'ai besoin d'un NS(Mutable)AttributedString et certains mots dans cette chaîne doit être donné une couleur différente. J'ai essayé ceci:

NSString *text = @"This is the text and i want to replace something";

NSDictionary *attributes = @ {NSForegroundColorAttributeName : [UIColor redColor]};
NSMutableAttributedString *subString = [[NSMutableAttributedString alloc] initWithString:@"AND" attributes:attributes];

NSMutableAttributedString *newText = [[NSMutableAttributedString alloc] initWithString:text];

newText = [[newText mutableString] stringByReplacingOccurrencesOfString:@"and" withString:[subString mutableString]];

"Et" doivent être en majuscules un rouge.

La documentation dit que mutableString garde les mappages d'attributs. Mais avec mon remplaçant-chose, je n'ai plus de attributedString sur le côté droit de la cession (dans la dernière ligne de mon code-extrait).

Comment puis-je obtenir ce que je veux? 😉

source d'informationauteur mjay