Search code examples
xcodecolorsnsarraynsattributedstring

NSAttributedString new color each line (Strings from array)


I am trying display coloured text stored in an array in UITextView. NSAttributedStrings usually works, but I want to display each objectAtIndex item in the new line and change the color of the text. Here is my code and it displays weird output:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];

for (NSString *str in self.tvInputArray){

    if ([str containsString:@"-"] ) {

        NSAttributedString *atrString = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n",str] attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];

        [attributedString appendAttributedString:atrString];
    }

    else if ([str containsString:@"+"] ) {

        NSAttributedString *atrString2 = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n",str] attributes:@{NSForegroundColorAttributeName: [UIColor blueColor]}];

        [attributedString appendAttributedString:atrString2];
    }
}

[selectedItemsTV setText:[NSString stringWithFormat:@"%@", attributedString]];
  1. Loop through an array to check for signs "-" & "+"
  2. Assign color according to "-" & "+"
  3. Display attributed string in the UITextView

The weird output in actual UITextView is:

MyString - {
NSColor = "UIDeviceRGBColorSpace 0.760784 0.235294 0.623529 1";
} 

Can somebody point me the right direction please?


Solution

  • Got it, I forgot to pass it to the UITextView as an attributed string:

     [selectedItemsTV setAttributedText:attributedString];
    

    Hope this will help to someone