Questa domanda può essere un duplicato di this one. Ma le risposte non funzionano per me e voglio essere più specifico.Modificare gli attributi delle sottostringhe in una stringa NSAattributed
Ho un NSString
, ma ho bisogno di un NS(Mutable)AttributedString
e alcune delle parole in questa stringa devono avere un colore diverso. Ho provato questo:
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]];
Il "e" deve essere maiuscolo un rosso.
La documentazione dice che mutableString mantiene i mapping degli attributi. Ma con la mia sostituzione-cosa, non ho più attribuito Stringhe sul lato destro del compito (nell'ultima riga del mio codice-snippet).
Come posso ottenere quello che voglio? ;)
prima modifica la stringa. Quindi creare una nuova NSMutableAttributedString con la stringa modificata e quindi impostare l'attributo come colore rosso. Non è possibile modificare la stringa e aspettarsi che gli attributi vengano mantenuti. – croyneaus4u