Search code examples
iosobjective-ciphonensmutableattributedstring

Keep the colors of the textView text after appending NSSting


I'm using the next method to change the colors of few words in textView:

+(void)changeColorToTextObject : (UITextView *)textView ToColor : (UIColor *)color FromLocation : (int)location length : (int)length
{
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: textView.attributedText];

    [text addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(location, length)];
    [textView setAttributedText: text];
}

and it looks like this: enter image description here

but when i'm adding new value to this text the color are gone.

myTextView.text = [myTextView.text stringByAppendingString:newStr];

And it looks like this:

enter image description here

How can I keep the colors like before with the new string?


Solution

  • Instead of myTextView.text = [myTextView.text stringByAppendingString:newStr]; use:

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:myTextView.attributedText];
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:newStr];
    [text appendAttributedString:newAttrString];
    myTextView.attributedText = text;
    

    Your code does not work because you are assigning to a new string to the text property of myTextView. text is just just a NSString property and thus is not able to display colors or other things that can be displayed using an NSAttributedString.

    Note that writing myTextView.attributedText = text; calls the setter of the property attributedText and thus is 100% equivalent to [myTextView setAttributedText:text];, just a different notation.