Search code examples
iphoneuilabelnsattributedstring

UILabel is not displaying its correct value even if it is giving the newly assigned value in console


I have a UILabel which is displayed as a question. Its successfully displaying the question text which has been assigned to it programmatically. But later according to one if else condition, I have to change text in the label.Specifically I want to display an asterik(*) mark at the end of the string if that is a mandatory question.The * should be in red color and rest of the text should be in black.But it displays only the question not the * mark.If I try to print the questLabel.text it is giving the question with * mark at the end.Here is the code that I am trying

  questText = questLabel.text;
         questText = [questText stringByAppendingString:@"✶"];
 NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:questText];
         NSMutableAttributedString *text =
            [[NSMutableAttributedString alloc]
             initWithAttributedString: str];
             int length = (int)text.length;
            [text addAttribute:NSForegroundColorAttributeName
                         value:[UIColor redColor]
                         range:NSMakeRange(length-1, 1)];
            [questLabel setAttributedText: text];

If I try to print the value of questLabel.attributedText :

Question{
}✶{
    NSColor = "UIDeviceRGBColorSpace 1 0 0 1";
}

And the value for questLabel.text is :Question✶

Please help me out with this..Thanks in advance..


Solution

  • You should change your code to this.

    NSString *questText = questLabel.text;
    questText = [questText stringByAppendingString:@"✶"];
    
    NSMutableAttributedString *text =
    [[NSMutableAttributedString alloc] initWithString:questText];
    
    int length = (int)text.length;
    
    [text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length-1)];
    [text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(length-1, 1)];
    [questLabel setAttributedText: text];