iosuilabelnsattributedstringuicolortextcolor

How to make a single UILabel with multiple colors


I want to create a single uilabel with 2 colors. the first color is black and the other one is blue.

i could use multiple uilabel in it but i want to have only single uilabel. Is there any way i can implement this?

This should be the output.

enter image description here

and here is my code:

UILabel * lblPostContent = [[UILabel alloc] initWithFrame:CGRectMake((ICON_PADDING*1.5), 42, container.frame.size.width-30, 34)];
lblPostContent.numberOfLines =0;
[lblPostContent setFont:[UIFont systemFontOfSize:11]];
[lblPostContent setText:[NSString stringWithFormat:@"I just scored %d points at %@ using the iBowl app", score, LuckyStrikes]];
[container addSubview:lblPostContent];

Solution

  • Yo should use attributes... like this

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:yourString];
    [text addAttribute: NSForegroundColorAttributeName value: [UIColor blackColor] range: NSMakeRange(0, TXTTOBEBLACKLENGTH)];
    [text addAttribute: NSForegroundColorAttributeName value: [UIColor blueColor] range: NSMakeRange(TXTTOBEBLACKLENGTH, TXTTOBEBLBLUELENGTH)];
    [lblPostContent setAttributedText: text];