UILabel 没有显示其正确的值,即使它在控制台中给出了新分配的值

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

我有一个显示为问题的 UILabel。它成功地显示了以编程方式分配给它的问题文本。但后来根据一个 if else 条件,我必须更改 label.Specifically 中的文本 我想在字符串末尾显示一个星号 (*) 标记,如果这是强制性的 question.The * 应该是红色,其余文本应该在 black.But 它只显示问题而不是 * mark.If 我尝试打印 questLabel.text 它在 end.Here 是我正在尝试的代码

  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];

如果我尝试打印 questLabel.attributedText 的值:

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

questLabel.text 的值为:问题✶

请帮我解决这个问题..提前致谢..

你应该把代码改成这样。

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];

你也可以试试这个

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.questLabel.text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];

NSMutableAttributedString *starString = [[NSMutableAttributedString alloc] initWithString:@"✶" attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

[string appendAttributedString:starString];

[self.questLabel setAttributedText:string];