Search code examples
iosobjective-cuitableviewnsmutableattributedstring

How to set multiple color text in table view in ios


I have a string ... Share Pictures .I want to show the Share in different color.I used NSMutableAttributedString to change the color of that part of the string.But when I am setting the cell.textLabel.text using the following string it doesn't work.Any other way to do this?

This way it doesn't work.

NSMutableAttributedString *string3 = [[NSMutableAttributedString alloc]initWithString:@"Share pictures "];
[string3 addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, 4)];
NSString *tempStr3 = @"with your friends.";
NSString *finalString3 = [NSString stringWithFormat:@"%@%@" , string3, tempStr3];
[menuTextArray addObject:finalString3];

And in table view datasource method.

 cell.textLabel.text = [menuTextArray objectAtIndex:indexPath.row];

Solution

  • You need to add only NSMutableAttributedString into your menuTextArray:

    NSMutableAttributedString *yourString = [[NSMutableAttributedString alloc]initWithString:@"Share pictures with your friends"];
    [yourString addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, 4)];
    [menuTextArray addObject:yourString];
    

    then set attributedText

    cell.textLabel.attributedText = [menuTextArray objectAtIndex:indexPath.row];