0

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?

nburk
  • 22,409
  • 18
  • 87
  • 132
Asi Givati
  • 1,348
  • 1
  • 15
  • 31

1 Answers1

1

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.

nburk
  • 22,409
  • 18
  • 87
  • 132
  • For some reason the append method is crushing the app. I tried the code: NSMutableAttributedString *text = (NSMutableAttributedString *)myTextView.attributedText; NSAttributedString *str = [[NSAttributedString alloc]initWithString:newStr]; [text appendAttributedString:str]; myTextView.attributedText = text; – Asi Givati Mar 24 '15 at 15:19
  • are you getting an error message? make sure that `newString` is _not_ `nil` in any case :) – nburk Mar 24 '15 at 15:21
  • Yes i'm sure :) there is value in the str – Asi Givati Mar 24 '15 at 15:38
  • ah sorry, there was a glitch in my code!! you need to use use `[text appendAttributedString:newAttrString];` instead of `[text appendAttributedString:newString];` – nburk Mar 24 '15 at 15:39