Search code examples
iosnsattributedstring

I am trying to set attributed string to UITableViewCell's text label I am using following code


NSDictionary * dic = [arrayForTableView objectAtIndex:indexPath.row];

NSNumber* lostPets = [dic valueForKey:@"lostPets"];
NSNumber * foundPets = [dic valueForKey:@"foundPets"];
NSString * breed = [dic valueForKey:@"breed"];

NSMutableAttributedString* message = [[NSMutableAttributedString alloc] init];
//set text
[message appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ (",breed]]];
[message appendAttributedString:[[NSAttributedString alloc] initWithString:[foundPets stringValue] attributes:@{
                                                                                             NSFontAttributeName : [UIColor greenColor]
                                                                                             }]];
[message appendAttributedString:[[NSAttributedString alloc] initWithString:@"), ("]];
[message appendAttributedString:[[NSAttributedString alloc] initWithString:[lostPets stringValue] attributes:@{
                                                                                             NSFontAttributeName : [UIColor redColor]
                                                                                             }]];
[message appendAttributedString:[[NSAttributedString alloc] initWithString:@")"]];

cell.textLabel.attributedText = message;

When I run the code I get following exception

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICachedDeviceRGBColor ctFontRef]: unrecognized selector sent to instance

I tried to debug the code but unable to get the point of crash.


Solution

  • Why are you passing a color to the font attribute?

    You are creating this dictionary:

    @{ NSFontAttributeName : [UIColor greenColor] }
    

    Those two don't match. Either replace NSFontAttributeName with NSForegroundColorAttributeName or replace [UIColor greenColor] with a proper UIFont reference. The change depends on what you need. Do you want to set the color or set the font?